using System;
using System.Threading.Tasks;
using FwProject.Distribution.Dto;
using FwProject.Core.Distribution;
using X.PagedList;
using Abp.Runtime.Caching;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp;
using System.Collections.Generic;
using System.Linq;
using AutoMapper.QueryableExtensions;
using FwProject.Core.Restaurant;
using FwProject.Manager;
using Abp.Authorization;
using FwProject.Restaurant.Dto;
using FwProject.Restaurant;
using FwProject.TypeNumber;
using FwProject.Users;
using FwProject.Car;
using FwProject.PublicService.SqlExec;
using Abp.UI;
using FwProject.Authorization.Users;
using System.Data;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore;
using Abp.RemoteEventBus;
using FwProject.Distribution.Dto.Statistics;
using FwProject.Core.TypeNumber;
using FwProject.TypeNumber.Dto;
using System.Diagnostics;
using FwProject.Core.Car;
using FwProject.Comm;
using FwProject.Core.SettlementInfoModel;
using FwProject.PrePaymentInfo;
using Abp.Events.Bus;
using FwProject.EventBusData;
using System.Linq.Dynamic.Core;

namespace FwProject.Distribution
{
    [AbpAuthorize]
    public class DistributionAppService : FwProjectAppServiceBase, IDistributionAppService
    {
        /// <summary>
        /// 第一步声明数据库访问领域对象
        /// </summary>
        private readonly IRepository<DistributionInfo, Guid> _repositoryDistributionInfo;
        private readonly IRepository<RestaurantUserInfo, Guid> _repositoryRestaurantUserInfo;
        private readonly IRepository<DistributionInfoDetails, Guid> _repositoryDistributionInfoDetails;
        private readonly IRepository<ReceiptInfoBySettlementModel, Guid> _repositoryReceiptInfoBySettlementModel;
        private readonly IRestaurantTypeNumberAppService _RestaurantTypeNumberAppService;
        private readonly IRestaurantUserAppService _IRestaurantUserAppService;
        private readonly ITypeNumberInfoAppService _ITypeNumberInfoAppService;
        private readonly IUserAppService _IUserAppService;
        private readonly DistributionInfoManager _distributionManager;
        public readonly IRepository<LoadCar, Guid> _repositoryLoadCar;
        private readonly LoadCarRecoveryManager _loadCarRecoveryManager;
        private readonly IDistributionDetailsAppService _idistributionDetailsAppService;
        private readonly ISqlExecuter _sqlExecuter;
        private readonly IRestaurantAppService _restaurantAppService;
        private readonly IRepository<User, long> _repositoryUser;
        private readonly ICarInfoAppService _ICarInfoAppService;
        private readonly ICacheManager _catchmanager;
        private readonly IRepository<TypeNumberInfo, Guid> _repositoryTypeNumberInfo;
        private readonly IRepository<RestaurantInfo, Guid> _repositoryRestaurantInfo;
        private readonly IRepository<LoadingCarInfo, Guid> _repositoryLoadingCarInfo;
        private readonly IRepository<LoadCarRecovery, Guid> _repositoryLoadCarRecovery;
        private readonly IRepository<DriverLine, Guid> _repositoryLoadDriverLine;
        public readonly IRepository<SettlementInfo, Guid> _repositorySettlementInfo;
        private readonly IRepository<PrePaymentInfoModel, Guid> _repositoryPrePayment;

        private readonly IRepository<DistributionLine, Guid> _repositoryDistributionLine;


        private readonly LoadingCarManager _loadingCarManager;

        private readonly IRepository<CarInfo, Guid> _repositoryCarInfo;
        private readonly IRepository<ReceiptInfoModel, Guid> _repositoryReceiptInfo;


        public IGuidGenerator _guid { get; set; }//guid 对象
        public IObjectMapper _map { get; set; }//缓存对象
        public IEventBus EventBus { get; set; }
        public DistributionAppService(
            LoadingCarManager loadingCarManager,
            IRepository<LoadCarRecovery, Guid> repositoryLoadCarRecovery,
            IRepository<User, long> repositoryUser,
            IRepository<DistributionInfo, Guid> repositoryDistributionInfo,
            ICacheManager catchmanager, IRepository<RestaurantUserInfo, Guid> repositoryRestaurantUserInfo,
            IRepository<DistributionInfoDetails, Guid> repositoryDistributionInfoDetails,
            IDistributionDetailsAppService idistributionDetailsAppService, DistributionInfoManager distributionManager,
            IRestaurantTypeNumberAppService RestaurantTypeNumberAppService, ITypeNumberInfoAppService ITypeNumberInfoAppService,
            IRestaurantUserAppService IRestaurantUserAppService, ISqlExecuter sqlExecuter,
            IUserAppService IUserAppService, ICarInfoAppService ICarInfoAppService,
            IRestaurantAppService restaurantAppService,
            IRepository<TypeNumberInfo, Guid> repositoryTypeNumberInfo,
            IRepository<RestaurantInfo, Guid> repositoryRestaurantInfo,
            LoadCarRecoveryManager loadCarRecoveryManager,
            IRepository<CarInfo, Guid> repositoryCarInfo,
            IRepository<LoadCar, Guid> repositoryLoadCar,
            IRepository<LoadingCarInfo, Guid> repositoryLoadingCarInfo,
            IRepository<DriverLine, Guid> repositoryLoadDriverLine,
            IRepository<SettlementInfo, Guid> repositorySettlementInfo,
            IRepository<PrePaymentInfoModel, Guid> repositoryPrePayment,
            IRepository<ReceiptInfoModel, Guid> repositoryReceiptInfo,
            IRepository<DistributionLine, Guid> repositoryDistributionLine,
                IRepository<ReceiptInfoBySettlementModel, Guid> repositoryReceiptInfoBySettlementModel)
        {
            _repositoryReceiptInfoBySettlementModel = repositoryReceiptInfoBySettlementModel;
            _guid = SequentialGuidGenerator.Instance;
            _repositoryLoadDriverLine = repositoryLoadDriverLine;
            _repositoryLoadingCarInfo = repositoryLoadingCarInfo;
            _repositoryLoadCar = repositoryLoadCar;
            _loadingCarManager = loadingCarManager;
            _loadCarRecoveryManager = loadCarRecoveryManager;
            _repositoryLoadCarRecovery = repositoryLoadCarRecovery;
            _repositoryUser = repositoryUser;
            _restaurantAppService = restaurantAppService;
            _ICarInfoAppService = ICarInfoAppService;
            _IUserAppService = IUserAppService;
            _IRestaurantUserAppService = IRestaurantUserAppService;
            _ITypeNumberInfoAppService = ITypeNumberInfoAppService;
            _RestaurantTypeNumberAppService = RestaurantTypeNumberAppService;
            _idistributionDetailsAppService = idistributionDetailsAppService;
            _repositoryDistributionInfo = repositoryDistributionInfo;//构造函数注入
            _catchmanager = catchmanager;
            _repositoryRestaurantUserInfo = repositoryRestaurantUserInfo;
            _repositoryDistributionInfoDetails = repositoryDistributionInfoDetails;
            _distributionManager = distributionManager;
            _sqlExecuter = sqlExecuter;

            _repositoryReceiptInfo = repositoryReceiptInfo;

            _repositoryTypeNumberInfo = repositoryTypeNumberInfo;
            _repositoryRestaurantInfo = repositoryRestaurantInfo;
            _repositoryCarInfo = repositoryCarInfo;
            _repositorySettlementInfo = repositorySettlementInfo;
            _repositoryPrePayment = repositoryPrePayment;
            _repositoryDistributionLine = repositoryDistributionLine;
            EventBus = NullEventBus.Instance;

        }
        public IRemoteEventBus remoteEventBus { get; set; }//缓存对象
        public DistributionAppService()
        {

            remoteEventBus = NullRemoteEventBus.Instance;
        }

        [Obsolete("过期不在使用UpdateDistributionStauts")]
        public async Task UpdateDistributionInfoStatus()
        {
            var catcheventDate = new RemoteEventData("Update")
            {
                Data = { ["model"] = "1" }
            };
            await remoteEventBus.PublishAsync("SystemDistributionInfoStatus", catcheventDate);
        }

        /// <summary>
        /// 测试调用
        /// </summary>
        /// <returns></returns>

        [Obsolete]
        public async Task Test()
        {
            var catcheventDate = new RemoteEventData("RemoteTest")
            {
                Data = { ["model"] = "1" }
            };
            await remoteEventBus.PublishAsync("DistributionDetailsMessage", catcheventDate);
        }

        /// <summary>
        /// 创建回收
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task BackProduct(List<LoadCarRecoveryDto> input, Guid disId)
        {

            foreach (var item in input)
            {
                var model = _map.Map<LoadCarRecovery>(item);
                model.DistributionInfoId = disId;
                model.Id = _guid.Create();
                await _loadCarRecoveryManager.CreateLoadcar(model);
            }

        }

        #region App获取当前餐厅的店存数
        public async Task<Tuple<int>> GetSotck(Guid Restaurantid)
        {
            var user = (await GetCurrentUserAsync());
            int stock = 0;
            var rm = await _repositoryRestaurantInfo.GetAsync(Restaurantid);
            Tuple<int> tuple = Tuple.Create<int>(rm.RealStock);
            return tuple;
        }
        #endregion
        #region App餐厅列表查看当日配送统计
        /// <summary>
        /// 餐厅列表获取当日配送和回收的总数据显示
        /// Item1 是配送 Item2  是回收
        /// </summary>
        /// <returns></returns>
        public async Task<Tuple<int, int>> GetDistributionInfoAllInfo()
        {

            if (AbpSession.UserId.HasValue == false)
            {
                throw new UserFriendlyException("当前司机未登录！");
            }
            var user = (await GetCurrentUserAsync());
            var list = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => EF.Functions.DateDiffDay(o.CreationTime, DateTime.Now) == 0 && o.FactoryinfoId == user.FactoryinfoId && o.CreatorUserId == AbpSession.UserId.Value).SelectMany(s => s.DistributionInfoListDetails);
            Tuple<int, int> tuple = Tuple.Create(list.Sum(o => o.Distributioncount), list.Sum(o => o.Recoverycount));
            return tuple;
        }

        #endregion
        #region  App创建一个配送订单
        /// <summary>
        /// App创建一个配送订单
        /// </summary>
        /// <returns>The create.</returns>
        /// <param name="input">Input.</param>
        public async Task<Guid> Create(DistributionInpuDto input)
        {
            var user = (await GetCurrentUserAsync());
            var model = _map.Map<DistributionInfo>(input);
            model.Id = _guid.Create();
            model.FactoryinfoId = user.FactoryinfoId;
            ///修改店存值
            var rm = await _repositoryRestaurantInfo.GetAsync(input.Restaurantid);

           // model.DistributionStock = input.Stock + input.DetailsInputDtos.Sum(s => s.Distributioncount + s.Givecount - s.Backboxcount - s.Recoverycount);
            rm.RealStock = input.Stock;
            model.DistributionInfoListDetails = new List<DistributionInfoDetails>();
            foreach (var item in input.DetailsInputDtos)
            {
                DistributionInfoDetails t = new DistributionInfoDetails();
                t = _map.Map<DistributionInfoDetails>(item);
                t.Id = _guid.Create();
                t.CreatorUserId = input.CreatorUserId;
                t.DistributionInfoId = model.Id;
                var typeModel = _repositoryTypeNumberInfo.Get(item.TypeNumberInfoId.Value);

                t.TypeNumberName = typeModel.Name;
                ///当自身默认绑定了该型号
                if (item.RestaurantTypenNumberInfoId != null)
                {
                    var itemRestaurantTypenNumber = (await (_RestaurantTypeNumberAppService.GetByIdAsync(item.RestaurantTypenNumberInfoId.Value)));
                    t.TypeNumberPrice = itemRestaurantTypenNumber.Price;
                }
                else
                {
                    t.TypeNumberPrice = 0.0m;
                }
                t.Sumprice = t.TypeNumberPrice * ((t.Distributioncount - t.Backboxcount) * typeModel.Count - t.Backnumbercount - t.Damagecount);
                // t.TypeNumberInfoId = (await (_RestaurantTypeNumberAppService.GetByIdAsync(t.RestaurantTypenNumberInfoId.Value))).TypeNumberId;
                model.DistributionInfoListDetails.Add(t);


            }
            foreach (var item in model.DistributionInfoListDetails)
            {
                var loadingModel = _loadingCarManager.GetByTypeNumberId(item.TypeNumberInfoId.Value, model.LoadCarId.Value);
                if (loadingModel == null)
                {
                    LoadingCarInfo loadingCarInfo = new LoadingCarInfo();
                    loadingCarInfo.LoadCarId = model.LoadCarId;
                    loadingCarInfo.Countproduct = 0;
                    loadingCarInfo.TypeNumberInfoId = item.TypeNumberInfoId.Value;
                    _loadingCarManager.CreateSync(loadingCarInfo);
                }
            }
            model.TotalPrice = model.DistributionInfoListDetails.Sum(o => o.Sumprice);


            await _distributionManager.CreateDistribution(model);
            try
            {
                CreatedDistributionEventData data = new CreatedDistributionEventData();
                data.FactoryinfoId = user.FactoryinfoId.Value;
                data.Id = model.Id;
                data.RestaurantId = model.Restaurantid.Value;
                data.ActionType = ActionType.创建配送;
                data.UserId = AbpSession.UserId.Value;
                data.MessageContent = $"创建配送";
                EventBus.Trigger(data);//领域事件去处理
            }
            catch (Exception exe)
            {

                Logger.Error("记录配送日志错误", exe);
            }
            ///缓存修改
            var catcheventDate = new RemoteEventData(RemoteTypeHelp.TypeModelCatch)
            {
                Data = { [RemoteTypeHelp.Model] = nameof(LoadingCarInfo) }
            };
            remoteEventBus.Publish(RemoteTypeHelp.TopicSystemCatch, catcheventDate);
            return model.Id;
        }
        #endregion
        #region app司机修改配送数据 后期把该方法移动到配送服务中
        /// <summary>
        /// 司机修改配送数据
        /// </summary>
        /// <param name="distributionId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task EditAppDistribution(EditDistributionInpuDto inputList)
        {

            var user = (await GetCurrentUserAsync());
            var types = inputList.DetailsInputDtos.Select(o => o.TypeNumberInfoId);
            if (types.Distinct().Count() != types.Count())
                throw new UserFriendlyException(2, "不能添加重复的型号！！！");

            var model = await _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.Id == inputList.Id).FirstOrDefaultAsync();
            decimal TotalPrice = 0m;
            var typeNumber = await _RestaurantTypeNumberAppService.GetRestaurantTypeNumAsync(model.Restaurantid.Value);
            ///修改店存值
            var rm = await _repositoryRestaurantInfo.GetAsync(model.Restaurantid.Value);
            ///注意需要前端店存如果是修改就得到当时的店存值?这里差一个实际存数
            model.DistributionStock = inputList.DistributionStock;
            //rm.RealStock + inputList.DetailsInputDtos.Sum(s => s.Distributioncount + s.Givecount - s.Backboxcount - s.Recoverycount);
            rm.RealStock = inputList.Stock;

            EditDistributionEventData data = new EditDistributionEventData();
            data.Id = model.Id;
            data.RestaurantId = model.Restaurantid.Value;
            data.ActionType = ActionType.配送修改;
            data.UserId = AbpSession.UserId.Value;
            data.FactoryinfoId = user.FactoryinfoId.Value;
            try
            {
                foreach (var item in model.DistributionInfoListDetails)
                {
                    //获取绑定型号
                    var inputModel = inputList.DetailsInputDtos.Where(o => o.Id == item.Id).FirstOrDefault();
                    if (inputModel != null)
                    {
                        if (await GetLoadCarTypeNumberByRemain(model.LoadCarId.Value, inputModel.TypeNumberInfoId.Value, inputModel.Id.Value, inputModel.Distributioncount, inputModel.Backboxcount, inputModel.Givecount))
                        {
                            if (item.RestaurantTypenNumberInfoId != null)
                            {
                                var tempTypeNumber = typeNumber.Where(o => o.Id == item.RestaurantTypenNumberInfoId.Value).FirstOrDefault();
                                inputModel.Sumprice = tempTypeNumber.Price * ((inputModel.Distributioncount - inputModel.Backboxcount) * tempTypeNumber.TypeNumberInfoModel.Count - inputModel.Backnumbercount - inputModel.Damagecount);
                                inputModel.TypeNumberPrice = tempTypeNumber.Price;

                                TotalPrice += inputModel.Sumprice;
                            }

                            var updatemodel = _map.Map(inputModel, item);
                            data.EventOldDataDistributionInfoDetails = item;//原始对象
                            data.EventNewDataDistributionInfoDetails = updatemodel;//新对象
                            try
                            {
                                EventBus.Trigger(data);//领域事件去处理
                            }
                            catch (Exception exe)
                            {

                                Logger.Error("记录配送日志错误", exe);
                            }
                            await _repositoryDistributionInfoDetails.UpdateAsync(updatemodel);
                        }
                    }
                }
                try
                {
                    var t = inputList.DetailsInputDtos.Where(o => o.Id.HasValue == false);
                    if (t.Count() > 0)
                    {
                        foreach (var item in t)
                        {

                            var typeModel = _repositoryTypeNumberInfo.Get(item.TypeNumberInfoId.Value);

                            if (item.Distributioncount > 0)
                            {
                                var m = _repositoryLoadCar.GetAllIncluding(o => o.LoadingCarInfoList).Where(o => o.Id == model.LoadCarId).FirstOrDefault();
                                if (m.LoadingCarInfoList.Where(o => o.TypeNumberInfoId == item.TypeNumberInfoId.Value).FirstOrDefault() == null)
                                    throw new UserFriendlyException($"该{typeModel.Name}未装车不可配送,可回收");
                            }


                            var updatemodel = _map.Map<DistributionInfoDetails>(item);
                            updatemodel.Id = _guid.Create();
                            updatemodel.Restaurantid = model.Restaurantid.Value;
                            updatemodel.TypeNumberName = typeModel.Name;
                            updatemodel.Sumprice = 0.0m;
                            updatemodel.DistributionInfoId = model.Id;
                            updatemodel.Pricestatus = Pricestatus.已配送;
                            updatemodel.TypeNumberPrice = 0.0m;
                            if (await GetLoadCarTypeNumberByRemain(model.LoadCarId.Value, updatemodel.TypeNumberInfoId.Value, updatemodel.Id, updatemodel.Distributioncount, updatemodel.Backboxcount, updatemodel.Givecount))
                            {
                                if (item.RestaurantTypenNumberInfoId != null)
                                {
                                    var tempTypeNumber = typeNumber.Where(o => o.Id == item.RestaurantTypenNumberInfoId.Value).FirstOrDefault();
                                    updatemodel.Sumprice = tempTypeNumber.Price * ((updatemodel.Distributioncount - updatemodel.Backboxcount) * tempTypeNumber.TypeNumberInfoModel.Count - updatemodel.Backnumbercount - updatemodel.Damagecount);
                                    updatemodel.TypeNumberPrice = tempTypeNumber.Price;
                                    TotalPrice += updatemodel.Sumprice;
                                }
                                _repositoryDistributionInfoDetails.InsertAndGetId(updatemodel);


                            }
                        }
                    }
                    model.TotalPrice = TotalPrice;
                    model.Pricestatus = Pricestatus.已配送;
                }
                catch (Exception exe)
                {
                    Logger.Error("添加新型号失败", exe);
                    throw new UserFriendlyException("有未装车型号");
                }
                //新添加的型号

            }
            catch (Exception exe)
            {
                Logger.Error("型号修改错误", exe);
                throw new UserFriendlyException("型号数量超出当前车辆型号数量请检查");
            }
            ///后台生成当前日结的账单
            var remoteEventData = new RemoteEventData(RemoteTypeHelp.TYPEDistributionBySettlementInfo)
            {
                Data = { [RemoteTypeHelp.MODELID] = model.Id }
            };
            remoteEventBus.Publish(RemoteTypeHelp.TopicDistribution, remoteEventData);
            ///修改完成缓存修改
            var catcheventDate = new RemoteEventData(RemoteTypeHelp.TypeModelCatch)
            {
                Data = { [RemoteTypeHelp.Model] = nameof(DistributionInfoDetails) }
            };
            remoteEventBus.Publish(RemoteTypeHelp.TopicSystemCatch, catcheventDate);
        }
        /// <summary>
        ///修改的时候判断车辆是否满足修改条件
        /// </summary>
        /// <param name="loadCarId"></param>
        /// <param name="typeNumberId"></param>
        /// <param name="disDetailsId"></param>
        /// <param name="Distributioncount"></param>
        /// <param name="Backboxcount"></param>
        /// <param name="Givecount"></param>
        /// <returns></returns>
        private async Task<bool> GetLoadCarTypeNumberByRemain(Guid loadCarId, Guid typeNumberId, Guid disDetailsId, int Distributioncount, int Backboxcount, int Givecount)
        {

            bool flag = true;
            try
            {
                var model = (await GetLoadCarCache).Where(o => o.Id == loadCarId).FirstOrDefault();
                if (model != null)
                {
                    var t = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.LoadCarId == loadCarId);
                    List<DistributionInfoDetails> list = new List<DistributionInfoDetails>();
                    foreach (var item in t)
                    {
                        ///获取所有的配送信息
                        list.AddRange(item.DistributionInfoListDetails);
                    }
                    var count = list.Where(o => o.Id != disDetailsId).GroupBy(o => o.TypeNumberInfoId).Where(o => o.Key == typeNumberId).Sum(o => o.Sum(k => (k.Distributioncount + k.Givecount - k.Backboxcount))); //10
                    //装车查看是否存在装车信息
                    var loadmodel = model.LoadingCarInfoList.Where(o => o.TypeNumberInfoId == typeNumberId).FirstOrDefault();
                    if (loadmodel != null)
                    {
                        var Countproduct = loadmodel.Countproduct;
                        if ((Countproduct + Backboxcount - count - Givecount) < Distributioncount)
                        {
                            flag = false;
                            throw new UserFriendlyException("型号数量超出当前车辆型号数量请检查");
                        }
                    }
                    else
                    {
                        ///如果装车型号不存在就添加一个装车信息
                        LoadingCarInfo dto = new LoadingCarInfo();
                        dto.Countproduct = Backboxcount;
                        dto.TypeNumberInfoId = typeNumberId;
                        dto.LoadCarId = loadCarId;
                        dto.Id = _guid.Create();
                        await _repositoryLoadingCarInfo.InsertAndGetIdAsync(dto);

                        var catcheventDate = new RemoteEventData(RemoteTypeHelp.TypeModelCatch)
                        {
                            Data = { [RemoteTypeHelp.Model] = nameof(LoadingCarInfo) }
                        };
                        remoteEventBus.Publish(RemoteTypeHelp.TopicSystemCatch, catcheventDate);
                    }


                }
            }
            catch (Exception exe)
            {
                System.Console.WriteLine($"EditDistribution:{exe.ToString()}");
                flag = false;
                throw new UserFriendlyException("型号异常请检查");
            }
            return flag;
        }
        #endregion
        #region App 获取当前车辆配送的餐厅数据
        /// <summary>
        /// 获取配送数据
        /// </summary>
        /// <param name="restaurantId"></param>
        /// <returns></returns>
        public async Task<DistributionDto> GetDistributionDetails(Guid restaurantId)
        {
            var user = await base.GetCurrentUserAsync();
            var model = (await GetLoadCarCache).Where(o => o.CarStatus == CarStatus.配送中 && o.DriverUserId == AbpSession.UserId.Value).FirstOrDefault();
            if (model != null)
            {
                var distributionModelList = _map.Map<DistributionDto>(_repositoryDistributionInfo.GetAll().Where(o => o.LoadCarId == model.Id && o.Restaurantid == restaurantId).FirstOrDefault());

                if (distributionModelList != null)
                {
                    if (distributionModelList.Id != Guid.Empty)
                        distributionModelList.DistributionInfoListDetails = _map.Map<List<DistributionDetailsDto>>(_repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel).Where(o => o.DistributionInfoId == distributionModelList.Id));
                }
                return distributionModelList;
            }
            return new DistributionDto();
        }
        #endregion
        #region 过期的接口从未吊用过
        /// <summary>
        /// 创建一个配送订单
        /// </summary>
        /// <returns>The create.</returns>
        /// <param name="input">Input.</param>
        public async Task Createorder(Guid id, DistributionInpuDto input)
        {
            var user = (await GetCurrentUserAsync());
            var model = _map.Map<DistributionInfo>(input);
            model.Id = id;
            model.FactoryinfoId = user.FactoryinfoId;
            model.DistributionInfoListDetails = new List<DistributionInfoDetails>();
            foreach (var item in input.DetailsInputDtos)
            {
                DistributionInfoDetails t = new DistributionInfoDetails();
                t = _map.Map<DistributionInfoDetails>(item);
                var k = (await (_RestaurantTypeNumberAppService.GetByIdAsync(item.RestaurantTypenNumberInfoId.Value)));
                t.Id = _guid.Create();
                t.DistributionInfoId = model.Id;
                t.RestaurantTypenNumberInfoId = item.RestaurantTypenNumberInfoId;
                t.TypeNumberName = _repositoryTypeNumberInfo.Get(item.TypeNumberInfoId.Value).Name;
                ///当自身默认绑定了该型号
                if (item.RestaurantTypenNumberInfoId != null)
                {
                    var itemRestaurantTypenNumber = (await (_RestaurantTypeNumberAppService.GetByIdAsync(item.RestaurantTypenNumberInfoId.Value)));
                    t.TypeNumberPrice = itemRestaurantTypenNumber.Price;
                }
                else
                {
                    t.TypeNumberPrice = 0.0m;
                }
                model.DistributionInfoListDetails.Add(t);
            }

            await _repositoryDistributionInfo.InsertAndGetIdAsync(model);
        }
        #endregion
        #region 后台调用生成确定收据
        /// <summary>
        /// 结账修改
        /// </summary>
        /// <returns>The update order.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="setOrderID">Set order identifier.</param>
        public async Task SetUpdateOrder(Guid id, Guid setOrderID)
        {
            var model = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.Id == id && o.Pricestatus == Pricestatus.未结账).FirstOrDefault();
            model.SettlementId = setOrderID;
            foreach (var item in model.DistributionInfoListDetails)
            {
                item.PricesId = setOrderID;
            }
            await _repositoryDistributionInfo.UpdateAsync(model);
        }
        #endregion
        #region App配送的时候返回不是默认装车型号数据
        /// <summary>
        ///App配送时获取不是默认的装车数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<TypeNumberInfoDtoDistribution>> GetNotDefaultTypeNumber(Guid disId)
        {
            var user = await UserManager.GetUserByIdAsync(AbpSession.UserId.Value);
            var list = (await _ITypeNumberInfoAppService.GetAllSystemTypeNumber()).Where(o => o.FactoryinfoId == user.FactoryinfoId);
            var Examinemodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.Id == disId).FirstOrDefault();
            List<TypeNumberInfoDtoDistribution> listTypeinfo = new List<TypeNumberInfoDtoDistribution>();
            if (Examinemodel != null)
            {
                ///获取所有的的配送记录
                var i = Examinemodel.DistributionInfoListDetails.Select(o => o.TypeNumberInfoId).ToList();
                if (i.Count() > 0)
                {
                    listTypeinfo = _map.Map<List<TypeNumberInfoDtoDistribution>>(list.Where(o => i.Any(t => o.Id == t) == false).ToList());
                    ///获取餐厅绑定的型号
                    var rTypeNumber = await _RestaurantTypeNumberAppService.GetRestaurantTypeNumAsync(Examinemodel.Restaurantid.Value);
                    listTypeinfo.ForEach(o =>
                    {
                        if (rTypeNumber.Any(t => t.TypeNumberId == o.Id))
                            o.RestaurantTypeNumberId = rTypeNumber.Where(k => k.TypeNumberId == o.Id).FirstOrDefault().Id;
                    });
                }
            }
            return listTypeinfo;
        }
        #endregion
        /// <summary>
        /// 重计金额
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task RecalculatePrice(Guid id)
        {
            var model = await _repositoryDistributionInfo.GetAsync(id);
            // var typenumber = await _RestaurantTypeNumberAppService.GetRestaurantTypeNumberAsync(model.Restaurantid.Value);
            // if (typenumber == null)
            //    throw new UserFriendlyException("该餐厅没有绑定该货品型号！");

            var details = await _idistributionDetailsAppService.GetDistributionByIdAsync(id);
            foreach (var item in details)
            {
                item.Sumprice = item.Distributioncount * item.TypeNumberInfoModel.Count * item.TypeNumberPrice;
                await _idistributionDetailsAppService.UpdatePrice(item.Id, item.Sumprice);
            }

            model.TotalPrice = details.Sum(o => o.Sumprice);
            await _distributionManager.UpdateDistribution(model);
        }



        /// <summary>
        /// 获取一个配送订单
        /// </summary>
        /// <returns>The by identifier async.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<DistributionDto> GetByIdAsync(Guid id)
        {
            var model = await _repositoryDistributionInfo.GetAsync(id);
            var t = _map.Map<DistributionDto>(model);
            t.DistributionInfoListDetails = await _idistributionDetailsAppService.GetDistributionDetailsDtoListAsync(t.Id);
            return t;
        }



        /// <summary>
        /// 司机获取餐厅订单列表
        /// </summary>
        /// <returns>The driver paged list async.</returns>
        /// <param name="pageIdx">Page index.</param>
        /// <param name="pageSize">Page size.</param>
        /// <param name="restaurantId">餐厅编号</param>
        /// <param name="begindateTime">Begindate time.</param>
        /// <param name="enddatetime">Enddatetime.</param>
        public async Task<IPagedList<DistributionHistoryDetailsDto>> GetRestaurantByDistributionPagedListAsync(int pageIdx, int pageSize, Guid restaurantId, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel);
            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));
            if (restaurantId != Guid.Empty)
                listmodel = listmodel.Where(o => o.Restaurantid == restaurantId);

            var t = await listmodel.Where(o => o.Restaurantid == restaurantId).OrderByDescending(m => m.CreationTime).ProjectTo<DistributionHistoryDetailsDto>().ToPagedListAsync(pageIdx, pageSize);
            return t;
        }

        #region App餐厅获取自己配送明细

        /// <summary>
        /// 餐厅获取自己的订单列表
        /// </summary>
        /// <returns>The restaurant paged list async.</returns>
        /// <param name="pageIdx">Page index.</param>
        /// <param name="pageSize">Page size.</param>
        /// <param name="begindateTime">Begindate time.</param>
        /// <param name="enddatetime">Enddatetime.</param>
        public async Task<IPagedList<RestaurantDisDetails>> GetSelfRestaurantByDistributionPagedListAsync(int pageIdx, int pageSize, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel);
            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            var model = _repositoryRestaurantUserInfo.GetAll().Where(o => o.EmployeeRestaurantId == AbpSession.UserId.Value).FirstOrDefault();

            return await listmodel.Where(o => o.Restaurantid == model.RestaurantInfoId).Join(_repositoryUser.GetAll(), i => i.CreatorUserId, n => n.Id, (i, n) => new RestaurantDisDetails
            {
                DriverUserName = n.Name,
                DriverMobile = n.Mobile,
                TotalPrice = i.TotalPrice,
                DistributionInfoListDetails = _map.Map<List<RestaurantDistributionDetailsListDto>>(i.DistributionInfoListDetails),
                CreatorUserId = i.CreatorUserId,
                CreationTime = i.CreationTime,
                Pricestatus = i.Pricestatus
            }).OrderByDescending(m => m.CreationTime).ToPagedListAsync(pageIdx, pageSize);
        }
        #endregion
        /// <summary>
        /// 配送列表
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<DistributionViewDto>> GetPagedListAsync(int pageIdx, int pageSize, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = LoadCarCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            return await listmodel.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId && (o.CarStatus == CarStatus.配送中 || o.CarStatus == CarStatus.回库审核中)).OrderByDescending(m => m.CreationTime).ToPagedListAsync(pageIdx, pageSize);

        }
        /// <summary>
        /// 配送列表导出
        /// </summary>
        /// <returns></returns>
        public async Task<List<DistributionViewDto>> GetExportDistributionListAsync()
        {
            var listmodel = LoadCarCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            return listmodel.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId && (o.CarStatus == CarStatus.配送中 || o.CarStatus == CarStatus.回库审核中)).OrderByDescending(m => m.CreationTime).ToList();
        }

        public async Task<IPagedList<DistributionDetailsView>> GetDetailsPagedListAsync(int pageIdx, int pageSize, string restaurantName, string driverName, /*string ExamineStatus,*/ DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = DistributionInfoCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            if (!string.IsNullOrEmpty(restaurantName))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));

            if (!string.IsNullOrEmpty(driverName))
                listmodel = listmodel.Where(o => o.CreatorUserId.ToString() == driverName);

            //if (!string.IsNullOrEmpty(ExamineStatus))
            //    listmodel = listmodel.Where(o => o.ExamineStatus.ToString()==ExamineStatus);

            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            return await listmodel.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId).OrderByDescending(m => m.CreationTime).ToPagedListAsync(pageIdx, pageSize);

        }
        /// <summary>
        /// 查询配送的明细
        /// </summary>
        /// <param name="restaurantName"></param>
        /// <param name="driverName"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public List<DistributionDetailsView> GetDetailsCount(string restaurantName, string driverName, DateTime? beginTime, DateTime? endTime)
        {
            var model = DistributionInfoCatch.AsQueryable();

            if (!string.IsNullOrEmpty(restaurantName))
                model = model.Where(o => o.RestaurantName.Contains(restaurantName));
            if (!string.IsNullOrEmpty(driverName))
                model = model.Where(o => o.CreatorUserId.ToString() == driverName);
            if (beginTime.HasValue)
                model = model.Where(o => o.CreationTime >= beginTime);
            if (endTime.HasValue)
                model = model.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            return model.ToList();
        }
        /// <summary>
        /// 获取型号单价为0的餐厅列表
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantTypeNumberListDto>> GetRestaurantTypeNumberListAsync(int pageIdx, int pageSize)
        {
            var listmodel = RestaurantTypeNumberCatche.AsQueryable();

            var list = listmodel.GroupBy(o => o.RestaurantName);

            List<RestaurantTypeNumberListDto> rtlist = new List<RestaurantTypeNumberListDto>();

            foreach (var item in list)
            {
                RestaurantTypeNumberListDto dto = new RestaurantTypeNumberListDto();
                if (item.Count() > 0)
                {
                    dto.RestaurantName = item.First().RestaurantName;
                    dto.RestaurantAddress = item.First().RestaurantAddress;
                    dto.Name = item.First().Name;
                    dto.Mobile = item.First().Mobile;
                    dto.typeNumberLists = new List<TypeNumberListModel>();
                    foreach (var temp in item)
                    {
                        TypeNumberListModel model = new TypeNumberListModel()
                        {
                            Id = temp.RestaurantTypeNumberId,
                            TypeNumberName = temp.TypeNumberName,
                            Price = temp.Price
                        };
                        dto.typeNumberLists.Add(model);
                    }
                }
                rtlist.Add(dto);
            }

            return await rtlist.ToPagedListAsync(pageIdx, pageSize);
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="restaurantName"></param>
        /// <param name="driverName"></param>
        /// <param name="begindateTime"></param>
        /// <param name="enddatetime"></param>
        /// <returns></returns>
        public async Task<List<DistributionDetailsView>> GetExportDetailsAsync(string restaurantName, string driverName, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = DistributionInfoCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            if (!string.IsNullOrEmpty(restaurantName))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));

            if (!string.IsNullOrEmpty(driverName))
                listmodel = listmodel.Where(o => o.CreatorUserId.ToString() == driverName);


            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            return listmodel.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId).OrderByDescending(m => m.CreationTime).ToList();

        }


        /// <summary>
        /// 根据收据查看配送明细
        /// </summary>
        /// <param name="settlementId"></param>
        /// <returns></returns>
        public async Task<List<DistributionDto>> GetDistributionInfoAsync(Guid settlementId)
        {
            var model = await _repositoryDistributionInfo.GetAllIncluding(o => o.RestaurantInfoModel, o => o.DistributionInfoListDetails).Where(o => o.SettlementId == settlementId).ToListAsync();
            return _map.Map<List<DistributionDto>>(model);
        }



        /// <summary>
        /// 配送签收列表
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<DistributionDetailsView>> GetSignPagedListAsync(int pageIdx, int pageSize, string restaurantName, string pricestatus, string driverName, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = DistributionInfoCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            if (!string.IsNullOrEmpty(restaurantName))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));

            if (!string.IsNullOrEmpty(pricestatus))
                listmodel = listmodel.Where(o => o.Pricestatus.ToString() == pricestatus);

            if (!string.IsNullOrEmpty(driverName))
                listmodel = listmodel.Where(o => o.CreatorUserId.ToString() == driverName);

            if (begindateTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            listmodel = listmodel.Where(o => o.Pricestatus != Pricestatus.已配送);
            return await listmodel.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId).OrderByDescending(m => m.CreationTime).ToPagedListAsync(pageIdx, pageSize);

        }
        /// <summary>
        /// 配送签收导出
        /// </summary>
        /// <returns></returns>
        public async Task<List<DistributionDetailsView>> GetExportSignListAsync(string restaurantName, string pricestatus, string driverName, DateTime? beginTime, DateTime? endTime)
        {
            var listmodel = DistributionInfoCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            if (!string.IsNullOrEmpty(restaurantName))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));

            if (!string.IsNullOrEmpty(pricestatus))
                listmodel = listmodel.Where(o => o.Pricestatus.ToString() == pricestatus);

            if (!string.IsNullOrEmpty(driverName))
                listmodel = listmodel.Where(o => o.CreatorUserId.ToString() == driverName);

            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            listmodel = listmodel.Where(o => o.Pricestatus != Pricestatus.已配送);
            return listmodel.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId).OrderByDescending(m => m.CreationTime).ToList();

        }

        /// <summary>
        /// 获取产品未支付的配送信息
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<DistributionDto>> GetPageNotPay(int pageIdx, int pageSize, Guid Restaurantid, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel);
            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            return await listmodel.Where(O => O.Restaurantid == Restaurantid && (O.Pricestatus == Pricestatus.未结账 || O.Pricestatus == Pricestatus.已制单) && O.SettlementId == null).OrderByDescending(m => m.CreationTime).ProjectTo<DistributionDto>().ToPagedListAsync(pageIdx, pageSize);
        }
        public async Task<IPagedList<DistributionDto>> GetAppPageNotPay(int pageIdx, int pageSize, Guid Restaurantid, DateTime? begindateTime, DateTime? enddatetime)
        {
            var restaurantModel = await _restaurantAppService.GetByIdAsync(Restaurantid);
            if (restaurantModel.EmployeeDriverid != AbpSession.UserId.Value)
                throw new UserFriendlyException("该餐厅不属于你的配送范围");

            var listmodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel);
            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            var model = await listmodel.Where(O => O.Restaurantid == Restaurantid && (O.Pricestatus == Pricestatus.未结账 || O.Pricestatus == Pricestatus.已制单) && O.SettlementId == null).OrderByDescending(m => m.CreationTime).ProjectTo<DistributionDto>().ToPagedListAsync(pageIdx, pageSize);
            return model;
        }

        /// <summary>
        /// 查询所有未结账的信息该餐厅
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <param name="begindateTime"></param>
        /// <param name="enddatetime"></param>
        /// <returns></returns>
        public async Task<IPagedList<DistributionDto>> GetSelfRestaurantByDistributionNotPayPagedListAsync(int pageIdx, int pageSize, Guid restaurantId, DateTime? begindateTime, DateTime? enddatetime)
        {
            var listmodel = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel);
            if (begindateTime != null)
                listmodel = listmodel.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                listmodel = listmodel.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));
            if (restaurantId != Guid.Empty)
                listmodel = listmodel.Where(o => o.Restaurantid == restaurantId);

            var t = await listmodel.Where(o => o.Restaurantid == restaurantId && (o.Pricestatus == Pricestatus.未结账 || o.Pricestatus == Pricestatus.已制单) && o.SettlementId == null).OrderByDescending(m => m.CreationTime).ProjectTo<DistributionDto>().ToPagedListAsync(pageIdx, pageSize);
            foreach (var item in t)
            {
                item.DistributionInfoListDetails = await _idistributionDetailsAppService.GetDistributionDetailsDtoListAsync(item.Id);
            }
            return t;
        }

        /// <summary>
        /// 首页报表
        /// </summary>
        /// <returns></returns>
        public async Task<Tuple<CarShopInfo, List<AppTopRestaurantDto>>> GetSelRept()
        {
            Tuple<CarShopInfo, List<AppTopRestaurantDto>> tuple = Tuple.Create<CarShopInfo, List<AppTopRestaurantDto>>(new CarShopInfo(), new List<AppTopRestaurantDto>());
            try
            {
                var user = await base.GetCurrentUserAsync();
                var ruser = _repositoryRestaurantUserInfo.GetAll().Where(o => o.EmployeeRestaurantId == AbpSession.UserId.Value).FirstOrDefault();
                if (ruser == null)
                    throw new UserFriendlyException("如需配送餐具请联系App平台绑定餐厅!");

                var RestaurantId = ruser.RestaurantInfoId;
                var li = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel).Where(o => o.Restaurantid == RestaurantId).OrderByDescending(m => m.CreationTime);
                CarShopInfo carinfo = new CarShopInfo();
                ////// 获取实际配送情况
                var kmodel = await li.GroupBy(o => new { o.TypeNumberInfoId, o.TypeNumberInfoModel }).Select(o => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = o.Key.TypeNumberInfoId.Value,
                    RestaurantTypeNumber = _map.Map<TypeNumberInfoDto>(o.Key.TypeNumberInfoModel),
                    Distributioncount = o.Sum(k => k.Distributioncount),
                    Exchangegoodscount = o.Sum(k => k.Exchangegoodscount),
                    Givecount = o.Sum(k => k.Givecount),
                    Recoverycount = o.Sum(k => k.Recoverycount),
                    Damagecount = o.Sum(k => k.Damagecount),
                    Backboxcount = o.Sum(k => k.Backboxcount),
                    Backnumbercount = o.Sum(k => k.Backnumbercount)

                }).ToListAsync();

                carinfo.LoadIngInfoOutPutDto = kmodel;

                var list = _restaurantAppService.GetTopRestaurant();
                tuple = Tuple.Create<CarShopInfo, List<AppTopRestaurantDto>>(carinfo, list);
            }
            catch (Exception exe)
            {
                throw new UserFriendlyException("服务繁忙", exe);

            }

            return tuple;
        }
        #region App首页获取餐厅的配送报表
        public async Task<List<CarShopInfo>> GetSelfRestaurantSelRept(int page, int pageseize, Pricestatus pricestatus, Guid? settlementInfoId, DateTime? beginTime, DateTime? endTime)
        {
            List<CarShopInfo> Carlist = new List<CarShopInfo>();
            try
            {
                var RestaurantId = _repositoryRestaurantUserInfo.GetAll().Where(o => o.EmployeeRestaurantId == AbpSession.UserId.Value).FirstOrDefault()?.RestaurantInfoId;
                var collection = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel).Where(o => o.Restaurantid == RestaurantId && o.Pricestatus == pricestatus);
                var user = await base.GetCurrentUserAsync();
                var typeNubers = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
                if (settlementInfoId != Guid.Empty)
                    collection = collection.Where(o => o.SettlementId == settlementInfoId);

                if (beginTime != null)
                    collection = collection.Where(o => o.CreationTime >= beginTime);

                if (endTime != null)
                    collection = collection.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

                // var li = await _repositoryDistributionInfoDetails.GetAllIncluding(o => o.RestaurantTypenNumberInfoModel).Where(o => RestaurantIds.Any(s => s == o.DistributionInfoId)).ProjectTo<DistributionDetailsDto>().ToPagedListAsync(page,pageseize);
                var listcollection = await collection.OrderByDescending(m => m.CreationTime).ToPagedListAsync(page, pageseize);


                foreach (var kitem in listcollection)
                {
                    var userModel = await _IUserAppService.GetByIdUserAsync(kitem.CreatorUserId.Value);
                    CarShopInfo carinfo = new CarShopInfo();
                    carinfo.DistributionInfo = _map.Map<FwProject.Restaurant.Dto.Distribution>(kitem);
                    carinfo.DrvierName = userModel.Name;
                    carinfo.DrvierMobile = userModel.Mobile;
                    carinfo.PlatesNumber = (await _ICarInfoAppService.GetByIdAsync(kitem.CreatorUserId.Value)).PlatesNumber;

                    ////// 获取实际配送情况
                    var kmodel = await kitem.DistributionInfoListDetails.GroupBy(o => o.TypeNumberInfoId).Select(o => new LoadIngInfoOutPutDto
                    {
                        TypeNumberInfoId = o.Key.Value,
                        RestaurantTypeNumber = o.Join(typeNubers, t => t.TypeNumberInfoId, s => s.Id, (t, s) => _map.Map<TypeNumberInfoDto>(s)).FirstOrDefault(),
                        Distributioncount = o.Sum(k => k.Distributioncount),
                        Recoverycount = o.Sum(k => k.Recoverycount),
                        Exchangegoodscount = o.Sum(k => k.Exchangegoodscount),
                        Damagecount = o.Sum(k => k.Damagecount),
                        Givecount = o.Sum(k => k.Givecount),
                        Backboxcount = o.Sum(k => k.Backboxcount),
                        Backnumbercount = o.Sum(k => k.Backnumbercount),

                    }).ToListAsync();

                    carinfo.LoadIngInfoOutPutDto = kmodel;
                    carinfo.CreationTime = kitem.CreationTime;

                    Carlist.Add(carinfo);
                    carinfo.LoadCarId = kitem.Id;
                }
            }
            catch (Exception exe)
            {

                Logger.Info("GetSelfRestaurantSelReptc异常", exe);
            }

            return Carlist;
        }
        #endregion
        #region app餐厅端获取所有未确认配送的信息
        /// <summary>
        /// 获取所有未确认配送订单信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<SelfRestaurantEnterDto>> GetSelfRestaurantEnter()
        {
            var Id = AbpSession.UserId.Value;
            var restaurantModel = await _IRestaurantUserAppService.GetByUserRestaurant(Id);
            if (restaurantModel == null)
                throw new UserFriendlyException("未绑定餐厅信息");

            var model = _repositoryDistributionInfo.GetAllIncluding(o => o.CarInfoModel, o => o.DistributionInfoListDetails).Where(o => o.Pricestatus == Pricestatus.已配送 && o.Restaurantid == restaurantModel.RestaurantInfoId);
            var list = model.Join(_repositoryUser.GetAll(), i => i.CarInfoModel.EmployeeCarUserId, b => b.Id, (i, b) => new SelfRestaurantEnterDto
            {
                Id = i.Id,
                CarUserName = b.Name,
                CreationTime = i.CreationTime,
                SelfRestaurantDetailsList = new SelfRestaurantDetails
                {
                    Distributioncount = i.DistributionInfoListDetails.Sum(o => o.Distributioncount),
                    Recoverycount = i.DistributionInfoListDetails.Sum(o => o.Recoverycount),
                    Exchangegoodscount = i.DistributionInfoListDetails.Sum(o => o.Exchangegoodscount),
                    Damagecount = i.DistributionInfoListDetails.Sum(o => o.Damagecount),
                    Givecount = i.DistributionInfoListDetails.Sum(o => o.Givecount),
                    Backboxcount = i.DistributionInfoListDetails.Sum(o => o.Backboxcount),
                    Backnumbercount = i.DistributionInfoListDetails.Sum(o => o.Backnumbercount)
                }
            }).OrderByDescending(m => m.CreationTime);
            return list.ToList();

            //var list = _map.Map<List<DistributionDto>>((await GetCache).Where(o => o.Pricestatus == Pricestatus.已配送 && o.Restaurantid == restaurantModel.RestaurantInfoId).OrderByDescending(m => m.CreationTime));

            //foreach (var item in list)
            //{
            //    item.CarInfoModel.CarUser = (await _ICarInfoAppService.GetByCarIdAsync(item.Carinfoid)).CarUser;
            //}
            //return list;
        }
        #endregion
        #region 后台操作方法
        /// <summary>
        /// 获取配送明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DistributionDetailsView GetDetailsById(Guid id)
        {
            var model = DistributionInfoCatch.Where(o => o.Id == id).FirstOrDefault();
            return model;
        }

        /// <summary>
        /// 获取配送打印信息
        /// </summary>
        /// <param name="id">配送Id</param>
        /// <returns></returns>
        //public async Task GetPrintOutputDtoAsync(Guid id)
        //{
        //    var query = _repositoryDistributionInfo.GetAll().Where(o => o.Id == id);
        //}


        /// <summary>
        /// 修改配送状态
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task EditStatusEnter(List<DistributionUpdateStatusDto> dto)
        {
            foreach (var item in dto)
            {
                var model = await _repositoryDistributionInfo.GetAsync(item.DistributionCarId);
                model.Pricestatus = item.DistributionStatus;
                await _distributionManager.UpdateDistribution(model);
            }

        }
        /// <summary>
        /// 根据司机编号查询出司机的配送明细
        /// </summary>
        /// <param name="Driverid"></param>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public async Task<List<DistributionDto>> GetDriverByRestaurant(long Driverid, DateTime? BeginTime, DateTime? EndTime)
        {

            var model = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel).Where(o => o.CreatorUserId == Driverid);
            if (BeginTime != null)
                model = model.Where(o => o.CreationTime >= BeginTime);

            if (EndTime != null)
                model = model.Where(o => o.CreationTime <= EndTime.Value.AddHours(24));

            var list = _map.Map<List<DistributionDto>>(model);

            foreach (var item in list)
            {
                item.DistributionInfoListDetails = await _idistributionDetailsAppService.GetDistributionDetailsDtoListAsync(item.Id);

            }
            return list;
        }


        /// <summary>
        /// 修改配送
        /// </summary>
        /// <returns>The update.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="input">Input.</param>
        public async Task EditDistribution(Guid id, DistributionInpuDto input, long CreatorUserId)
        {
            var user = await base.GetCurrentUserAsync();
            var car = await _ICarInfoAppService.GetByIdAsync(CreatorUserId);
            var model = await _repositoryDistributionInfo.GetAsync(id);
            if (model.SettlementId.HasValue)
                throw new UserFriendlyException("配送已被收据引用不可修改");

            var details = await _idistributionDetailsAppService.GetByIdDistributionDetailsListAsync(id);

            EditDistributionEventData data = new EditDistributionEventData();
            data.Id = model.Id;
            data.RestaurantId = model.Restaurantid.Value;
            data.ActionType = ActionType.配送修改;
            data.UserId = AbpSession.UserId.Value;
            data.FactoryinfoId = user.FactoryinfoId.Value;

            model.CreationTime = input.CreationTime;
            model.TotalPrice = input.TotalPrice;
            model.Stock = input.Stock;
            model.DistributionStock = input.DistributionStock;
            var rmodel = _repositoryRestaurantInfo.Get(model.Restaurantid.Value);
            if (rmodel.RealStock != input.Stock)
                rmodel.RealStock = input.Stock;

            await _distributionManager.UpdateDistribution(model);

            foreach (var item in input.DetailsInputDtos)
            {
                var m = await _repositoryDistributionInfoDetails.GetAsync(item.Id.Value);
               
                var updatemodel = _map.Map<DistributionInfoDetails>(item);
                updatemodel.CreationTime = input.CreationTime;
                _repositoryLoadingCarInfo.GetAll().Where(o => o.LoadCarId == model.LoadCarId && o.TypeNumberInfoId == item.TypeNumberInfoId).FirstOrDefault().Countproduct = updatemodel.Distributioncount;
                data.EventOldDataDistributionInfoDetails = m;
                data.EventNewDataDistributionInfoDetails = updatemodel;
                try
                {
                    EventBus.Trigger(data);//领域事件去处理
                }
                catch (Exception exe)
                {
                    Logger.Error("记录配送日志错误", exe);
                }
                await _idistributionDetailsAppService.Update(item.Id.Value, item);

            }
            ///后台生成当前日结的账单
            var remoteEventData = new RemoteEventData(RemoteTypeHelp.TYPEDistributionBySettlementInfo)
            {
                Data = { [RemoteTypeHelp.MODELID] = model.Id }
            };
            remoteEventBus.Publish(RemoteTypeHelp.TopicDistribution, remoteEventData);

            var disCatch = new RemoteEventData(RemoteTypeHelp.TypeModelCatch)
            {
                Data = { [RemoteTypeHelp.MODELID] = model.Id }
            };
            remoteEventBus.Publish(RemoteTypeHelp.TopicSystemCatch, disCatch);

        }
        public async Task<IPagedList<ReceivableDto>> GetReceivableListAsync(int page, int pagesize, string restaurantName, string driverName, DateTime? beginTime, DateTime? endTime)
        {
            var model = BillDetailsCatch.AsQueryable();
            var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);

            if (!string.IsNullOrEmpty(restaurantName))
                model = model.Where(o => o.RestaurantName.Contains(restaurantName));

            if (!string.IsNullOrEmpty(driverName))
                model = model.Where(o => o.CreatorUserId.ToString() == driverName);

            if (beginTime != null)
                model = model.Where(o => o.CreationTime >= beginTime);

            if (endTime != null)
                model = model.Where(o => o.CreationTime <= endTime.Value.AddHours(24));
            return await model.Where(o => o.FactoryinfoId == usermodel.FactoryinfoId && o.Pricestatus == Pricestatus.未结账).OrderByDescending(m => m.CreationTime).ToPagedListAsync(page, pagesize);
        }
        /// <summary>
        /// 应收查询
        /// </summary>
        /// <returns></returns>
        public async Task<ReceivableNewSummaryDto> GetReceivableAsync(int page, int pagesize, string restaurantName, string driverName, DateTime? beginTime, DateTime? endTime, DateTime? beginDate, DateTime? endDate, RestaurantPayStatus? RestaurantPayStatus, BalanceWayEnum? BalanceWayEnum)
        {
            #region Bygone
            //string where1 = "";
            //string where2 = "";
            //if (beginTime.HasValue)
            //{
            //    where1 = " and CreationTime>='" + beginTime + "'";
            //}
            //if (endTime.HasValue)
            //{
            //    endTime = endTime.Value.AddHours(24);
            //    where2 = " and CreationTime<='" + endTime + "'";
            //}
            //var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);
            //string sql = $@"select [RestaurantName]
            //                      ,[RestaurantAddress]
            //                      ,[Pricestatus]
            //                      ,SUM([TotalPrice]) as TotalPrice
            //                      ,[PlatesNumber]
            //                      ,[CreatorUserId]
            //                      ,[DriverName]
            //                      ,[DriverMobile] from V_BillDetails where Pricestatus=1 and FactoryinfoId='{usermodel.FactoryinfoId}'{where1}{where2} group by RestaurantName,RestaurantAddress,CreatorUserId,DriverName,PlatesNumber,DriverMobile,Pricestatus";

            //var listmodel = _sqlExecuter.FromDapperSqlQuery<ReceivableDto>(sql, null).AsQueryable();

            //if (!string.IsNullOrEmpty(restaurantName))
            //    listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));

            //if (!string.IsNullOrEmpty(driverName))
            //    listmodel = listmodel.Where(o => o.CreatorUserId.ToString() == driverName);

            //return await listmodel.ToPagedListAsync(page, pagesize);

            #endregion
            var user = await base.GetCurrentUserAsync();
            var query = _repositorySettlementInfo.GetAllIncluding(o => o.RestaurantInfoModel, o => o.EmployeeDriverDao).Where(o => o.FactoryinfoId == user.FactoryinfoId && o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核 && o.RestaurantPayStatus != Core.SettlementInfoModel.RestaurantPayStatus.作废).Select(o => new
            {
                Id = o.Id,
                Actualprice = o.Actualprice,
                BalanceWayEnum = o.BalanceWayEnum,
                CreationNumber = o.CreationNumber,
                CreatorUserId = o.CreatorUserId,
                CreationTime = o.CreationTime,
                DeliveryDate = o.DeliveryDate,
                Discountprice = o.Discountprice,
                ReceivedDiscount = o.ReceivedDiscount,
                RestaurantId = o.Restaurantid,
                RestaurantName = o.RestaurantInfoModel.RestaurantName,

                RestaurantPayStatus = o.RestaurantPayStatus,
                Totalprice = o.Totalprice,
                ReceivedPrice = o.ReceivedPrice,
                UsePrePayment = o.UsePrePayment,
                BeginTime = o.BeginTime,
                EndTime = o.EndTime
            }).Join(_repositoryRestaurantInfo.GetAll(), a => a.RestaurantId, b => b.Id, (a, b) => new ReceivableNewOutputDto
            {
                Id = a.Id,
                Actualprice = a.Actualprice,
                BalanceWayEnum = a.BalanceWayEnum,
                CreationNumber = a.CreationNumber,
                CreatorUserId = a.CreatorUserId,
                CreationTime = a.CreationTime,
                DeliveryDate = a.DeliveryDate,
                Discountprice = a.Discountprice,
                ReceivedDiscount = a.ReceivedDiscount,
                RestaurantName = a.RestaurantName,
                RestaurantPayStatus = a.RestaurantPayStatus,
                Totalprice = a.Totalprice,
                ReceivedPrice = a.ReceivedPrice,
                UsePrePayment = a.UsePrePayment,
                BeginTime = a.BeginTime,
                EndTime = a.EndTime,
                Driverid = b.EmployeeDriverid
            });
            if (beginTime.HasValue)
                query = query.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                query = query.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (beginDate.HasValue && endDate.HasValue)
            {
                query = query.Where(o => o.BeginTime.Value >= beginDate.Value && o.EndTime.Value <= endDate.Value);
            }

            if (!string.IsNullOrEmpty(driverName))
                query = query.Where(o => o.Driverid == long.Parse(driverName));


            if (!string.IsNullOrEmpty(restaurantName))
                query = query.Where(o => o.RestaurantName.Contains(restaurantName));

            if (RestaurantPayStatus.HasValue)
                query = query.Where(o => o.RestaurantPayStatus == RestaurantPayStatus.Value);

            if (BalanceWayEnum.HasValue)
                query = query.Where(o => o.BalanceWayEnum == BalanceWayEnum.Value);

            ReceivableNewSummaryDto dto = new ReceivableNewSummaryDto();
            dto.SumTotalPrice = query.Sum(o => o.Totalprice);
            dto.SumActualPrice = query.Sum(o => o.Actualprice);
            dto.SumReceivedPrice = query.Sum(o => o.ReceivedPrice);
            dto.SumTaskNotBackAmount = query.Sum(o => o.TaskNotBackAmount);
            dto.SumDiscountPrice = query.Sum(o => o.Discountprice);
            dto.SumReceivedDiscount = query.Sum(o => o.ReceivedDiscount);
            dto.SumTotalDiscount = query.Sum(o => o.TotalDiscount);

            dto.PageList = await query.OrderByDescending(o => o.CreationTime).ToPagedListAsync(page, pagesize);


            return dto;

        }

        /// <summary>
        /// 未收款餐厅--报表
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<NotReceivableDto>> GetNotReceivableRestaurantAsync(int pageIdx, int pageSize, string RestaurantName)
        {
            var user = await base.GetCurrentUserAsync();
            var model = _repositorySettlementInfo.GetAllIncluding(o => o.RestaurantInfoModel, o => o.EmployeeDriverDao).Where(o => o.FactoryinfoId == user.FactoryinfoId && o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核 && (o.RestaurantPayStatus == RestaurantPayStatus.未收款 || o.RestaurantPayStatus == RestaurantPayStatus.部分收款));

            var data = model.GroupBy(o => o.Restaurantid).Select(s => new
            {
                RestaurantId = s.Key,
                TotalPrice = s.Sum(x => x.Actualprice),
                ReceivedPrice = s.Sum(x => x.ReceivedPrice),
                UnCollectedPrice = s.Sum(x => x.Totalprice - x.ReceivedPrice - x.Discountprice - x.ReceivedDiscount - x.UsePrePayment)
            }).Join(_repositoryRestaurantInfo.GetAllIncluding(o => o.EmployeeDriver), a => a.RestaurantId, b => b.Id, (a, b) => new NotReceivableDto
            {
                RestaurantId = a.RestaurantId.Value,
                RestaurantName = b.RestaurantName,
                DriverName = b.EmployeeDriver.Name,
                TotalPrice = a.TotalPrice,
                ReceivedPrice = a.ReceivedPrice,
                UncollectedPrice = a.UnCollectedPrice
            });

            if (!string.IsNullOrEmpty(RestaurantName))
                data = data.Where(o => o.RestaurantName.Contains(RestaurantName));

            return await data.ToPagedListAsync(pageIdx, pageSize);
        }

        public async Task<List<NotReceivableDto>> GetNotReceivableListAsync(string RestaurantName)
        {
            var user = await base.GetCurrentUserAsync();
            var model = _repositorySettlementInfo.GetAllIncluding(o => o.RestaurantInfoModel, o => o.EmployeeDriverDao).Where(o => o.FactoryinfoId == user.FactoryinfoId && o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核 && (o.RestaurantPayStatus == RestaurantPayStatus.未收款 || o.RestaurantPayStatus == RestaurantPayStatus.部分收款));

            var data = model.GroupBy(o => o.Restaurantid).Select(s => new
            {
                RestaurantId = s.Key,
                TotalPrice = s.Sum(x => x.Actualprice),
                ReceivedPrice = s.Sum(x => x.ReceivedPrice),
                UnCollectedPrice = s.Sum(x => x.Totalprice - x.ReceivedPrice - x.Discountprice - x.ReceivedDiscount - x.UsePrePayment)
            }).Join(_repositoryRestaurantInfo.GetAllIncluding(o => o.EmployeeDriver), a => a.RestaurantId, b => b.Id, (a, b) => new NotReceivableDto
            {
                RestaurantId = a.RestaurantId.Value,
                RestaurantName = b.RestaurantName,
                DriverName = b.EmployeeDriver.Name,
                TotalPrice = a.TotalPrice,
                ReceivedPrice = a.ReceivedPrice,
                UncollectedPrice = a.UnCollectedPrice
            });

            if (!string.IsNullOrEmpty(RestaurantName))
                data = data.Where(o => o.RestaurantName.Contains(RestaurantName));

            return data.ToList();
        }
        /// <summary>
        /// 应收查询导出
        /// </summary>
        /// <returns></returns>
        public async Task<List<ReceivableNewOutputDto>> GetExportReceivableAsync(string restaurantName, string driverName, DateTime? beginTime, DateTime? endTime, DateTime? beginDate, DateTime? endDate, RestaurantPayStatus? RestaurantPayStatus, BalanceWayEnum? BalanceWayEnum)
        {
            var user = await base.GetCurrentUserAsync();
            var query = _repositorySettlementInfo.GetAllIncluding(o => o.RestaurantInfoModel, o => o.EmployeeDriverDao).Where(o => o.FactoryinfoId == user.FactoryinfoId && o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核).Select(o => new
            {
                Id = o.Id,
                Actualprice = o.Actualprice,
                BalanceWayEnum = o.BalanceWayEnum,
                CreationNumber = o.CreationNumber,
                CreatorUserId = o.CreatorUserId,
                CreationTime = o.CreationTime,
                DeliveryDate = o.DeliveryDate,
                Discountprice = o.Discountprice,
                ReceivedDiscount = o.ReceivedDiscount,
                RestaurantId = o.Restaurantid,
                RestaurantName = o.RestaurantInfoModel.RestaurantName,

                RestaurantPayStatus = o.RestaurantPayStatus,
                Totalprice = o.Totalprice,
                ReceivedPrice = o.ReceivedPrice,
                UsePrePayment = o.UsePrePayment,
                BeginTime = o.BeginTime,
                EndTime = o.EndTime
            }).Join(_repositoryRestaurantInfo.GetAll(), a => a.RestaurantId, b => b.Id, (a, b) => new ReceivableNewOutputDto
            {
                Id = a.Id,
                Actualprice = a.Actualprice,
                BalanceWayEnum = a.BalanceWayEnum,
                CreationNumber = a.CreationNumber,
                CreatorUserId = a.CreatorUserId,
                CreationTime = a.CreationTime,
                DeliveryDate = a.DeliveryDate,
                Discountprice = a.Discountprice,
                ReceivedDiscount = a.ReceivedDiscount,
                RestaurantName = a.RestaurantName,
                RestaurantPayStatus = a.RestaurantPayStatus,
                Totalprice = a.Totalprice,
                ReceivedPrice = a.ReceivedPrice,
                UsePrePayment = a.UsePrePayment,
                BeginTime = a.BeginTime,
                EndTime = a.EndTime,
                Driverid = b.EmployeeDriverid
            });
            if (beginTime.HasValue)
                query = query.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                query = query.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (beginDate.HasValue && endDate.HasValue)
            {
                query = query.Where(o => o.BeginTime.Value >= beginDate.Value && o.EndTime.Value <= endDate.Value);
            }

            if (!string.IsNullOrEmpty(driverName))
                query = query.Where(o => o.Driverid == long.Parse(driverName));


            if (!string.IsNullOrEmpty(restaurantName))
                query = query.Where(o => o.RestaurantName.Contains(restaurantName));

            if (RestaurantPayStatus.HasValue)
                query = query.Where(o => o.RestaurantPayStatus == RestaurantPayStatus.Value);

            if (BalanceWayEnum.HasValue)
                query = query.Where(o => o.BalanceWayEnum == BalanceWayEnum.Value);

            return query.ToList();
        }

        /// <summary>
        /// 餐厅配送统计
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantDistributionView>> GetRestaurantDistributionAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, string restaurantName, long? driverName)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            string where = $" where FactoryinfoId='{usermodel.FactoryinfoId}'";

            if (beginTime.HasValue)
                where += $" and CreationTime>='{beginTime}'";
            if (endTime.HasValue)
                where += $" and CreationTime<='{endTime.Value.AddHours(23).AddMinutes(59)}'";
            if (!string.IsNullOrEmpty(restaurantName))
                where += $" and RestaurantName like '%{restaurantName}%'";
            if (driverName.HasValue)
                where += $" and CreatorUserId={driverName}";

            string sql = $@"select RestaurantId,RestaurantName
                                      ,SUM(TotalPrice) as TotalPrice
                                      ,SUM(Backboxcount) as Backboxcount
                                      ,SUM(Backnumbercount)+SUM(BackboxBycount) as Backnumbercount
                                      ,SUM(Damagecount) as Damagecount
                                      ,SUM(Distributioncount) as Distributioncount
                                      ,SUM(DistributionBycount) as DistributionBycount
                                      ,SUM(Exchangegoodscount) as Exchangegoodscount
                                      ,SUM(ExchangegoodsBycount) as ExchangegoodsBycount
                                      ,SUM(Givecount) as Givecount
                                      ,SUM(Givebycount) as Givebycount
                                      ,SUM(Recoverycount) as Recoverycount
                                      ,SUM(RecoveryBycount) as RecoveryBycount
                                      from V_DistributionInfo {where} group by RestaurantId,RestaurantName ORDER BY SUM(TotalPrice) DESC";

            var model = await _sqlExecuter.IPagedListDynamicListFromSqlAsync<RestaurantDistributionView>(sql, "", pageIdx, pageSize);

            return model;
        }
        /// <summary>
        /// 餐厅配送统计导出
        /// </summary>
        /// <returns></returns>
        public async Task<List<RestaurantDistributionView>> GetRestaurantDistributionListAsync(DateTime? beginTime, DateTime? endTime, string restaurantName, long? driverName)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            string where = $" where FactoryinfoId='{usermodel.FactoryinfoId}'";

            if (beginTime.HasValue)
                where += $" and CreationTime>='{beginTime}'";
            if (endTime.HasValue)
                where += $" and CreationTime<='{endTime.Value.AddHours(24)}'";

            string sql = $@"select RestaurantName,CreatorUserId as DriverId,Name
                                    ,SUM(TotalPrice) as TotalPrice
                                      ,SUM(Backboxcount) as Backboxcount
                                      ,SUM(Backnumbercount)+SUM(BackboxBycount) as Backnumbercount
                                      ,SUM(Damagecount) as Damagecount
                                      ,SUM(Distributioncount) as Distributioncount
                                      ,SUM(DistributionBycount) as DistributionBycount
                                      ,SUM(Exchangegoodscount) as Exchangegoodscount
                                      ,SUM(ExchangegoodsBycount) as ExchangegoodsBycount
                                      ,SUM(Givecount) as Givecount
                                      ,SUM(Givebycount) as Givebycount
                                      ,SUM(Recoverycount) as Recoverycount
                                      ,SUM(RecoveryBycount) as RecoveryBycount
                                      from V_DistributionInfo {where} group by RestaurantName,CreatorUserId,Name";

            var model = _sqlExecuter.FromDapperSqlQuery<RestaurantDistributionView>(sql, null).AsQueryable();

            if (!string.IsNullOrEmpty(restaurantName))
                model = model.Where(o => o.RestaurantName.Contains(restaurantName));
            if (driverName.HasValue)
                model = model.Where(o => o.DriverId == driverName);

            return model.ToList();
        }
        /// <summary>
        /// 司机配送统计
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<RestaurantDistributionView>> GetDriverDistributionAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, long? driverName)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            string where = $" where FactoryinfoId='{usermodel.FactoryinfoId}'";

            if (beginTime.HasValue)
                where += $" and CreationTime>='{beginTime}'";
            if (endTime.HasValue)
                where += $" and CreationTime<='{endTime.Value.AddHours(24)}'";
            if (driverName.HasValue)
                where += $" and CreatorUserId={driverName}";

            string sql = $@"select CreatorUserId as DriverId,Name
                                      ,SUM(TotalPrice) as TotalPrice
                                      ,SUM(Backboxcount) as Backboxcount
                                      ,SUM(Backnumbercount)+SUM(BackboxBycount) as Backnumbercount
                                      ,SUM(Damagecount) as Damagecount
                                      ,SUM(Distributioncount) as Distributioncount
                                      ,SUM(DistributionBycount) as DistributionBycount
                                      ,SUM(Exchangegoodscount) as Exchangegoodscount
                                      ,SUM(ExchangegoodsBycount) as ExchangegoodsBycount
                                      ,SUM(Givecount) as Givecount
                                      ,SUM(Givebycount) as Givebycount
                                      ,SUM(Recoverycount) as Recoverycount
                                      ,SUM(RecoveryBycount) as RecoveryBycount
                                      from V_DistributionInfo {where} group by CreatorUserId,Name ORDER BY SUM(TotalPrice) DESC";

            return await _sqlExecuter.IPagedListDynamicListFromSqlAsync<RestaurantDistributionView>(sql, "", pageIdx, pageSize);
        }
        /// <summary>
        /// 司机配送统计导出
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="driverName"></param>
        /// <returns></returns>
        public async Task<List<ExportDriverDistributionDto>> GetExportDriverDistributionAsync(DateTime? beginTime, DateTime? endTime, long? driverName)
        {
            var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            string where = $" where FactoryinfoId='{usermodel.FactoryinfoId}'";

            if (beginTime.HasValue)
                where += $" and CreationTime>='{beginTime}'";
            if (endTime.HasValue)
                where += $" and CreationTime<='{endTime.Value.AddHours(24)}'";

            string sql = $@"select CreatorUserId as DriverId,Name
                                      ,SUM(TotalPrice) as TotalPrice
                                      ,SUM(Backboxcount) as Backboxcount
                                      ,SUM(Backnumbercount)+SUM(BackboxBycount) as Backnumbercount
                                      ,SUM(Damagecount) as Damagecount
                                      ,SUM(Distributioncount) as Distributioncount
                                      ,SUM(DistributionBycount) as DistributionBycount
                                      ,SUM(Exchangegoodscount) as Exchangegoodscount
                                      ,SUM(ExchangegoodsBycount) as ExchangegoodsBycount
                                      ,SUM(Givecount) as Givecount
                                      ,SUM(Givebycount) as Givebycount
                                      ,SUM(Recoverycount) as Recoverycount
                                      ,SUM(RecoveryBycount) as RecoveryBycount
                                      from V_DistributionInfo {where} group by CreatorUserId,Name";

            var listmodel = _sqlExecuter.FromDapperSqlQuery<ExportDriverDistributionDto>(sql, null).AsQueryable();

            if (driverName.HasValue)
                listmodel = listmodel.Where(o => o.DriverId == driverName);

            return listmodel.ToList();
        }

        public async Task<IPagedList<DistributionTypeNumberReportDto>> GetDistributiondetailsAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, long? driverName)
        {


            #region SQL
            //var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);

            //string where = $" and b.FactoryinfoId='{usermodel.FactoryinfoId}'";

            //if (beginTime.HasValue)
            //    where += $" and a.CreationTime>='{beginTime}'";
            //if (endTime.HasValue)
            //    where += $" and a.CreationTime<='{endTime.Value.AddHours(24)}'";
            //if (driverName.HasValue)
            //    where += $" and a.CreatorUserId={driverName}";

            //string sql = $@"select a.CreatorUserId as DriverId,
            //                        b.Name as DriverName,
            //                        c.Name,
            //                        Sum(Distributioncount) as Distributioncount,
            //                        Sum(Recoverycount) as Recoverycount,
            //                        Sum(Exchangegoodscount) as Exchangegoodscount,
            //                        Sum(Damagecount) as Damagecount,
            //                        Sum(Givecount) as Givecount,
            //                        Sum(Backboxcount) as Backboxcount,
            //                        Sum(Backnumbercount) as Backnumbercount from DistributionInfoDetails a,AbpUsers b,TypeNumberInfo c where a.CreatorUserId=b.id and a.TypeNumberInfoId = c.Id {where} group by a.CreatorUserId,b.Name,c.Name ORDER BY Sum(Distributioncount) DESC";

            //var listmodel = await _sqlExecuter.IPagedListDynamicListFromSqlAsync<DistributionTypeNumberDto>(sql, "", pageIdx, pageSize);

            //var list = listmodel.GroupBy(o => new { o.DriverId, o.DriverName }).Select(s => new DistributionTypeNumberReportDto
            //{
            //    DriverId = s.Key.DriverId,
            //    DriverName = s.Key.DriverName,
            //    TypeNumberModelList = s.Select(t => new TypeNumberModel
            //    {
            //        Name = t.Name,
            //        Distributioncount = t.Distributioncount,
            //        Damagecount = t.Damagecount,
            //        Backboxcount = t.Backboxcount,
            //        Backnumbercount = t.Backnumbercount,
            //        Exchangegoodscount = t.Exchangegoodscount,
            //        Givecount = t.Givecount,
            //        Recoverycount = t.Recoverycount
            //    }).ToList()
            //});

            //return await list.ToPagedListAsync(pageIdx, pageSize);
            #endregion
            var factoryinfoId = (await base.GetCurrentUserAsync()).FactoryinfoId;


            var distributionquery = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel);
            if (beginTime.HasValue)
                distributionquery = distributionquery.Where(o => o.CreationTime >= beginTime);
            if (endTime.HasValue)
                distributionquery = distributionquery.Where(o => o.CreationTime <= endTime.Value.AddDays(1));
            if (driverName.HasValue)
                distributionquery = distributionquery.Where(o => o.CreatorUserId == driverName);



            var query = distributionquery.GroupBy(o => o.CreatorUserId)
                .Join(_repositoryUser.GetAll().Where(o => o.FactoryinfoId == factoryinfoId), i => i.Key, j => j.Id, (d, u) => new DistributionTypeNumberReportDto
                {
                    DriverId = d.Key.Value,
                    DriverName = u.Name,
                    TypeNumberModelList = d.GroupBy(o => new { o.TypeNumberInfoId, o.TypeNumberName }).Select(o => new TypeNumberModel
                    {
                        Name = o.Key.TypeNumberName,
                        Distributioncount = o.Sum(s => s.Distributioncount),
                        DistributionNumbercount = o.Sum(s => s.Distributioncount * s.TypeNumberInfoModel.Count),
                        Backboxcount = o.Sum(s => s.Backboxcount),
                        Backnumbercount = o.Sum(s => s.Backnumbercount) + o.Sum(s => s.Backboxcount * s.TypeNumberInfoModel.Count),
                        Damagecount = o.Sum(s => s.Damagecount),
                        Exchangegoodscount = o.Sum(s => s.Exchangegoodscount),
                        ExchangegoodsNumbercount = o.Sum(s => s.Exchangegoodscount * s.TypeNumberInfoModel.Count),
                        Givecount = o.Sum(s => s.Givecount),
                        GiveNumbercount = o.Sum(s => s.Givecount * s.TypeNumberInfoModel.Count),
                        Recoverycount = o.Sum(s => s.Recoverycount),
                        RecoveryNumbercount = o.Sum(s => s.Recoverycount * s.TypeNumberInfoModel.Count),
                        Sumprice = o.Sum(s => s.Sumprice)
                    }).ToList()
                });

            return await query.OrderBy(o => o.DriverId).ToPagedListAsync(pageIdx, pageSize);
        }

        public async Task<List<ExportDistributionTypeNumberDto>> GetExportDistributionDetailsAsync(DateTime? beginTime, DateTime? endTime, long? driverName)
        {
            #region SQL
            //var usermodel = await _repositoryUser.GetAsync(AbpSession.UserId.Value);
            //string where = $" and b.FactoryinfoId='{usermodel.FactoryinfoId}'";

            //if (beginTime.HasValue)
            //    where += $" and a.CreationTime>='{beginTime}'";
            //if (endTime.HasValue)
            //    where += $" and a.CreationTime<='{endTime.Value.AddHours(24)}'";
            //string sql = $@"select a.CreatorUserId as DriverId,
            //                        b.Name as DriverName,
            //                        c.Name,
            //                        Sum(Distributioncount) as Distributioncount,
            //                        Sum(Recoverycount) as Recoverycount,
            //                        Sum(Exchangegoodscount) as Exchangegoodscount,
            //                        Sum(Damagecount) as Damagecount,
            //                        Sum(Givecount) as Givecount,
            //                        Sum(Backboxcount) as Backboxcount,
            //                        Sum(Backnumbercount) as Backnumbercount from DistributionInfoDetails a,AbpUsers b,TypeNumberInfo c where a.CreatorUserId=b.id and a.TypeNumberInfoId = c.Id {where} group by a.CreatorUserId,b.Name,c.Name";

            //var listmodel = _sqlExecuter.FromDapperSqlQuery<DistributionTypeNumberDto>(sql, null).AsQueryable();

            //if (!string.IsNullOrEmpty(driverName))
            //    listmodel = listmodel.Where(o => o.DriverId.ToString() == driverName);
            //var list = listmodel.GroupBy(o => new { o.DriverId, o.DriverName }).Select(s => new ExportDistributionTypeNumberDto
            //{
            //    DriverId = s.Key.DriverId,
            //    DriverName = s.Key.DriverName,
            //    TypeNumberModelList = s.Select(t => new ExportTypeNumber
            //    {
            //        Name = t.Name,
            //        Distributioncount = t.Distributioncount,
            //        Damagecount = t.Damagecount,
            //        Backboxcount = t.Backboxcount,
            //        Backnumbercount = t.Backnumbercount,
            //        Exchangegoodscount = t.Exchangegoodscount,
            //        Givecount = t.Givecount,
            //        Recoverycount = t.Recoverycount
            //    }).ToList()
            //});

            //return list.ToList();

            #endregion
            var factoryinfoId = (await base.GetCurrentUserAsync()).FactoryinfoId;


            var distributionquery = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel);
            if (beginTime.HasValue)
                distributionquery.Where(o => o.CreationTime >= beginTime);
            if (endTime.HasValue)
                distributionquery.Where(o => o.CreationTime <= endTime.Value.AddDays(1));
            if (driverName.HasValue)
                distributionquery.Where(o => o.CreatorUserId == driverName);



            var query = distributionquery.GroupBy(o => o.CreatorUserId)
                .Join(_repositoryUser.GetAll().Where(o => o.FactoryinfoId == factoryinfoId), i => i.Key, j => j.Id, (d, u) => new ExportDistributionTypeNumberDto
                {
                    DriverId = d.Key.Value,
                    DriverName = u.Name,
                    TypeNumberModelList = d.GroupBy(o => new { o.TypeNumberInfoId, o.TypeNumberName, o.TypeNumberPrice }).Select(o => new ExportTypeNumber
                    {
                        Name = o.Key.TypeNumberName,
                        Distributioncount = o.Sum(s => s.Distributioncount),
                        DistributionNumbercount = o.Sum(s => s.Distributioncount * s.TypeNumberInfoModel.Count),
                        Backboxcount = o.Sum(s => s.Backboxcount),
                        Backnumbercount = o.Sum(s => s.Backnumbercount) + o.Sum(s => s.Backboxcount * s.TypeNumberInfoModel.Count),
                        Damagecount = o.Sum(s => s.Damagecount),
                        Exchangegoodscount = o.Sum(s => s.Exchangegoodscount),
                        ExchangegoodsNumbercount = o.Sum(s => s.Exchangegoodscount * s.TypeNumberInfoModel.Count),
                        Givecount = o.Sum(s => s.Givecount),
                        GiveNumbercount = o.Sum(s => s.Givecount * s.TypeNumberInfoModel.Count),
                        Recoverycount = o.Sum(s => s.Recoverycount),
                        RecoveryNumbercount = o.Sum(s => s.Recoverycount * s.TypeNumberInfoModel.Count),
                    }).ToList()
                });

            return await query.ToListAsync();
        }

        /// <summary>
        /// 线路配送统计
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<DistributionLineViewList>> GetLineDistributionAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, Guid? line, string driverName)
        {
            #region OLD
            //var where1 = "";
            //var where2 = "";
            //if (beginTime.HasValue)
            //{
            //    where1 = " and a.CreationTime>='" + beginTime.Value + "'";
            //}
            //if (endTime.HasValue)
            //{
            //    endTime = endTime.Value.AddHours(24);
            //    where2 = " and a.CreationTime<='" + endTime.Value + "'";
            //}

            //var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);
            //string sql = $@"select LineName,e.Name as TypeNumberName,
            //                       SUM(b.Sumprice) as TotalPrice,
            //                       SUM(b.Backboxcount) as Backboxcount,
            //                       SUM(b.Backnumbercount) as Backnumbercount,
            //                       SUM(b.Damagecount) as Damagecount,
            //                       SUM(b.Distributioncount) as Distributioncount,
            //                       SUM(b.Exchangegoodscount) as Exchangegoodscount,
            //                       SUM(b.Givecount) as Givecount,
            //                       SUM(b.Recoverycount) as Recoverycount
            //                       from V_DistributionInfo a,DistributionInfoDetails b,DirverLine c,DistributionLine d,TypeNumberInfo e 
            //                       where a.id=b.DistributionInfoId and a.CreatorUserId=c.DriverId and c.LineId = d.Id and b.TypeNumberInfoId = e.Id and a.FactoryinfoId='{usermodel.FactoryinfoId}'{where1}{where2} group by LineName,e.Name";

            //var listmodel = _sqlExecuter.FromDapperSqlQuery<DistributionLineView>(sql, null).AsQueryable();

            //if (!string.IsNullOrEmpty(line))
            //    listmodel = listmodel.Where(o => o.LineName == line);
            ////if (!string.IsNullOrEmpty(driverName))
            ////    listmodel = listmodel.Where(o => o.DriverId.ToString() == driverName);

            //var list = listmodel.GroupBy(o => o.LineName);

            //List<DistributionLineViewList> lineList = new List<DistributionLineViewList>();

            //foreach (var item in list)
            //{
            //    DistributionLineViewList dto = new DistributionLineViewList();
            //    if (item.Count() > 0)
            //    {
            //        dto.LineName = item.First().LineName;
            //        dto.DistributionLineList = new List<DistributionLineModel>();
            //        foreach (var temp in item)
            //        {
            //            DistributionLineModel model = new DistributionLineModel()
            //            {
            //                TypeNumberName = temp.TypeNumberName,
            //                TotalPrice = temp.TotalPrice,
            //                Distributioncount = temp.Distributioncount,
            //                Damagecount = temp.Damagecount,
            //                Givecount = temp.Givecount,
            //                Backboxcount = temp.Backboxcount,
            //                Backnumbercount = temp.Backnumbercount,
            //                Exchangegoodscount = temp.Exchangegoodscount,
            //                Recoverycount = temp.Recoverycount
            //            };
            //            dto.DistributionLineList.Add(model);
            //        }
            //    }
            //    lineList.Add(dto);
            //}

            //return await lineList.ToPagedListAsync(pageIdx, pageSize);
            #endregion
            var user = await base.GetCurrentUserAsync();

            var details = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel);

            if (beginTime.HasValue)
                details = details.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                details = details.Where(o => o.CreationTime <= endTime.Value.AddDays(1));

            var dis = _repositoryLoadDriverLine.GetAll().Join(details, x => x.DriverId, y => y.CreatorUserId, (x, y) => new
            {
                x.LineId,
                y.TypeNumberName,
                y.Distributioncount,
                y.Givecount,
                y.Exchangegoodscount,
                y.Recoverycount,
                y.Damagecount,
                y.Backboxcount,
                y.Sumprice,
                DistributionSetcount = y.TypeNumberInfoModel.Count * y.Distributioncount,
                GiveSetcount = y.TypeNumberInfoModel.Count * y.Givecount,
                ExchangegoodsSetcount = y.TypeNumberInfoModel.Count * y.Exchangegoodscount,
                RecoverySetcount = y.TypeNumberInfoModel.Count * y.Recoverycount,
                Backnumbercount = y.Backnumbercount + y.TypeNumberInfoModel.Count * y.Backboxcount

            }).GroupBy(g => new { g.LineId, g.TypeNumberName }).Select(s => new DistributionLineModel
            {
                LineId = s.Key.LineId,
                TypeNumberName = s.Key.TypeNumberName,
                Distributioncount = s.Sum(sum => sum.Distributioncount),
                DistributionSetcount = s.Sum(sum => sum.DistributionSetcount),
                TotalPrice = s.Sum(sum => sum.Sumprice),
                Givecount = s.Sum(sum => sum.Givecount),
                GiveSetcount = s.Sum(sum => sum.GiveSetcount),
                Exchangegoodscount = s.Sum(sum => sum.Exchangegoodscount),
                ExchangegoodsSetcount = s.Sum(sum => sum.ExchangegoodsSetcount),
                Recoverycount = s.Sum(sum => sum.Recoverycount),
                RecoverySetcount = s.Sum(sum => sum.RecoverySetcount),
                Damagecount = s.Sum(sum => sum.Damagecount),
                Backboxcount = s.Sum(sum => sum.Backboxcount),
                Backnumbercount = s.Sum(sum => sum.Backnumbercount)
            });
            var lineQuery = _repositoryDistributionLine.GetAll().Where(o => o.FactoryInfoid == user.FactoryinfoId);
            if (line.HasValue)
                lineQuery = lineQuery.Where(o => o.Id == line);



            var query = lineQuery.Select(i =>
                new DistributionLineViewList
                {
                    FactoryInfoId = i.FactoryInfoid,
                    LineName = i.LineName,
                    DistributionLineList = dis.Where(o => o.LineId == i.Id).Select(s => new DistributionLineModel
                    {
                        TypeNumberName = s.TypeNumberName,
                        Distributioncount = s.Distributioncount,
                        DistributionSetcount = s.DistributionSetcount,
                        Givecount = s.Givecount,
                        GiveSetcount = s.GiveSetcount,
                        Exchangegoodscount = s.Exchangegoodscount,
                        ExchangegoodsSetcount = s.ExchangegoodsSetcount,
                        Recoverycount = s.Recoverycount,
                        RecoverySetcount = s.RecoverySetcount,
                        Damagecount = s.Damagecount,
                        Backboxcount = s.Backboxcount,
                        Backnumbercount = s.Backnumbercount,
                        TotalPrice = s.TotalPrice
                    }).ToList()

                });

            return await query.ToPagedListAsync(pageIdx, pageSize);
        }


        public async Task<List<DistributionLineViewList>> GetExportLineDistributionAsync(DateTime? beginTime, DateTime? endTime, Guid? line)
        {
            #region OLD
            //var where1 = "";
            //var where2 = "";
            //if (beginTime.HasValue)
            //{
            //    where1 = " and a.CreationTime>='" + beginTime.Value + "'";
            //}
            //if (endTime.HasValue)
            //{
            //    endTime = endTime.Value.AddHours(24);
            //    where2 = " and a.CreationTime<='" + endTime.Value + "'";
            //}

            //var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);
            //string sql = $@"select LineName,e.Name as TypeNumberName,
            //                       SUM(b.Sumprice) as TotalPrice,
            //                       SUM(b.Backboxcount) as Backboxcount,
            //                       SUM(b.Backnumbercount) as Backnumbercount,
            //                       SUM(b.Damagecount) as Damagecount,
            //                       SUM(b.Distributioncount) as Distributioncount,
            //                       SUM(b.Exchangegoodscount) as Exchangegoodscount,
            //                       SUM(b.Givecount) as Givecount,
            //                       SUM(b.Recoverycount) as Recoverycount
            //                       from V_DistributionInfo a,DistributionInfoDetails b,DirverLine c,DistributionLine d,TypeNumberInfo e 
            //                       where a.id=b.DistributionInfoId and a.CreatorUserId=c.DriverId and c.LineId = d.Id and b.TypeNumberInfoId = e.Id and a.FactoryinfoId='{usermodel.FactoryinfoId}'{where1}{where2} group by LineName,e.Name";

            //var listmodel = _sqlExecuter.FromDapperSqlQuery<DistributionLineView>(sql, null).AsQueryable();

            //if (!string.IsNullOrEmpty(line))
            //    listmodel = listmodel.Where(o => o.LineName == line);
            ////if (!string.IsNullOrEmpty(driverName))
            ////    listmodel = listmodel.Where(o => o.DriverId.ToString() == driverName);

            //var list = listmodel.GroupBy(o => o.LineName);

            //List<DistributionLineViewList> lineList = new List<DistributionLineViewList>();

            //foreach (var item in list)
            //{
            //    DistributionLineViewList dto = new DistributionLineViewList();
            //    if (item.Count() > 0)
            //    {
            //        dto.LineName = item.First().LineName;
            //        dto.DistributionLineList = new List<DistributionLineModel>();
            //        foreach (var temp in item)
            //        {
            //            DistributionLineModel model = new DistributionLineModel()
            //            {
            //                TypeNumberName = temp.TypeNumberName,
            //                TotalPrice = temp.TotalPrice,
            //                Distributioncount = temp.Distributioncount,
            //                Damagecount = temp.Damagecount,
            //                Givecount = temp.Givecount,
            //                Backboxcount = temp.Backboxcount,
            //                Backnumbercount = temp.Backnumbercount,
            //                Exchangegoodscount = temp.Exchangegoodscount,
            //                Recoverycount = temp.Recoverycount
            //            };
            //            dto.DistributionLineList.Add(model);
            //        }
            //    }
            //    lineList.Add(dto);
            //}

            //return lineList.ToList();
            #endregion
            var user = await base.GetCurrentUserAsync();

            var details = _repositoryDistributionInfoDetails.GetAll();

            if (beginTime.HasValue)
                details = details.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                details = details.Where(o => o.CreationTime <= endTime.Value.AddDays(1));

            var dis = _repositoryLoadDriverLine.GetAll().Join(details, x => x.DriverId, y => y.CreatorUserId, (x, y) => new
            {
                x.LineId,
                y.TypeNumberName,
                y.Distributioncount,
                y.Givecount,
                y.Exchangegoodscount,
                y.Recoverycount,
                y.Damagecount,
                y.Backboxcount,
                y.Backnumbercount,
                y.Sumprice
            }).GroupBy(g => new { g.LineId, g.TypeNumberName }).Select(s => new
            {
                LineId = s.Key.LineId,
                TypeNumberName = s.Key.TypeNumberName,
                Distributioncount = s.Sum(sum => sum.Distributioncount),
                TotalPrice = s.Sum(sum => sum.Sumprice),
                Givecount = s.Sum(sum => sum.Givecount),
                Exchangegoodscount = s.Sum(sum => sum.Exchangegoodscount),
                Recoverycount = s.Sum(sum => sum.Recoverycount),
                Damagecount = s.Sum(sum => sum.Damagecount),
                Backboxcount = s.Sum(sum => sum.Backboxcount),
                Backnumbercount = s.Sum(sum => sum.Backnumbercount)
            });
            var lineQuery = _repositoryDistributionLine.GetAll().Where(o => o.FactoryInfoid == user.FactoryinfoId);
            if (line.HasValue)
                lineQuery = lineQuery.Where(o => o.Id == line);


            var query = lineQuery.GroupJoin(dis, i => i.Id, j => j.LineId, (i, j) =>
                new DistributionLineViewList
                {
                    FactoryInfoId = i.FactoryInfoid,
                    LineName = i.LineName,
                    DistributionLineList = j.Select(s => new DistributionLineModel
                    {
                        TypeNumberName = s.TypeNumberName,
                        Distributioncount = s.Distributioncount,
                        Givecount = s.Givecount,
                        Exchangegoodscount = s.Exchangegoodscount,
                        Recoverycount = s.Recoverycount,
                        Damagecount = s.Damagecount,
                        Backboxcount = s.Backboxcount,
                        Backnumbercount = s.Backnumbercount,
                        TotalPrice = s.TotalPrice

                    }).ToList()

                });

            return await query.ToListAsync();
        }
        /// <summary>
        /// 配送差件汇总
        /// </summary>
        /// <returns></returns>
        public async Task<IPagedList<DistributionDiffView>> GetDistributionDiffAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, Guid? line, long? driverName)
        {

            #region Original
            //return await model.ToPagedListAsync(pageIdx, pageSize);
            #endregion
            var user = await base.GetCurrentUserAsync();
            var distributionQuery = _repositoryDistributionInfoDetails.GetAll();
            var lineQuery = _repositoryLoadDriverLine.GetAllIncluding(o => o.EmployeeDriver).Where(o => o.EmployeeDriver.FactoryinfoId == user.FactoryinfoId);

            if (beginTime.HasValue)
                distributionQuery = distributionQuery.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                distributionQuery = distributionQuery.Where(o => o.CreationTime <= endTime.Value.AddDays(1));

            if (line.HasValue)
                lineQuery = lineQuery.Where(o => o.LineId == line);

            if (driverName.HasValue)
                lineQuery = lineQuery.Where(o => o.DriverId == driverName);

            var lines = lineQuery.Select(o => o.DriverId);


            var query = distributionQuery.Where(o => lines.Any(s => s == o.CreatorUserId)).GroupBy(o => new { Year = o.CreationTime.Year, Month = o.CreationTime.Month, Day = o.CreationTime.Day }).OrderBy(o => o.Key.Day);

            var query2 = query.Select(o => new DistributionDiffView
            {

                DistributionDate = SqlFunction.DateFunction(o.Key.Year, o.Key.Month, o.Key.Day),
                Distributioncount = o.Sum(s => s.Distributioncount),
                Recoverycount = o.Sum(s => s.Recoverycount),
            });
            var data = await query2.ToPagedListAsync(pageIdx, pageSize);

            return data;
        }

        public async Task<List<DistributionDiffView>> GetExportDistributionDiffAsync(DateTime? beginTime, DateTime? endTime, Guid? LineId, long? DriverId)
        {
            #region Original
            //var where1 = "";
            //var where2 = "";
            //if (!string.IsNullOrEmpty(line))
            //{
            //    where1 = " and c.LineName='" + line + "'";
            //}
            //if (!string.IsNullOrEmpty(driverName))
            //{
            //    where2 = " and a.CreatorUserId='" + driverName + "'";
            //}

            //var usermodel = await _IUserAppService.GetByIdUserAsync(AbpSession.UserId.Value);
            //string sql = $@"select CONVERT([varchar](100),a.CreationTime , 23) as DistributionDate
            //                          ,SUM(Recoverycount) as Recoverycount
            //                          ,SUM(Distributioncount) as Distributioncount
            //                          ,(SUM(Recoverycount)-SUM(Distributioncount)) as Diff
            //                          from V_DistributionInfo a,DirverLine b,DistributionLine c where a.CreatorUserId=b.DriverId and b.LineId=c.Id and a.FactoryinfoId='{usermodel.FactoryinfoId}'{where1}{where2} group by CONVERT([varchar](100),a.CreationTime , 23)";

            //var model = _sqlExecuter.FromDapperSqlQuery<DistributionDiffView>(sql, null).AsQueryable();

            //if (beginTime.HasValue)
            //{
            //    model = model.Where(o => o.DistributionDate >= beginTime);
            //}
            //if (endTime.HasValue)
            //{
            //    model = model.Where(o => o.DistributionDate <= endTime.Value);
            //}

            //return model.ToList();
            #endregion

            var user = await base.GetCurrentUserAsync();
            var distributionQuery = _repositoryDistributionInfoDetails.GetAll();
            var lineQuery = _repositoryLoadDriverLine.GetAllIncluding(o => o.DistributionLineModel).Where(o => o.EmployeeDriver.FactoryinfoId == user.FactoryinfoId);

            if (beginTime.HasValue)
                distributionQuery = distributionQuery.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                distributionQuery = distributionQuery.Where(o => o.CreationTime <= endTime.Value.AddDays(1));

            if (LineId.HasValue)
                lineQuery = lineQuery.Where(o => o.LineId == LineId);

            if (DriverId.HasValue)
                lineQuery = lineQuery.Where(o => o.DriverId == DriverId);

            var query = distributionQuery.Join(lineQuery, o => o.CreatorUserId, j => j.DriverId, (i, j) => new
            {
                CreationTime = i.CreationTime,
                Distributioncount = i.Distributioncount,
                Recoverycount = i.Recoverycount,
            }).GroupBy(o => new { Year = o.CreationTime.Year, Month = o.CreationTime.Month, Day = o.CreationTime.Day }).Select(o =>
            new DistributionDiffView
            {
                DistributionDate = SqlFunction.DateFunction(o.Key.Year, o.Key.Month, o.Key.Day),
                Distributioncount = o.Sum(s => s.Distributioncount),
                Recoverycount = o.Sum(s => s.Recoverycount),
            });

            return await query.ToListAsync();
        }

        #region 配送报表

        public async Task<List<DistributionProductStatisticsDto>> GetDistributionProductStatisticsAsync(DateTime? beginTime, DateTime? endTime, string productName, string restaurant)
        {
            var user = await base.GetCurrentUserAsync();
            var typeNubers = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            var distributionDeails = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.RestaurantTypenNumberInfoModel, o => o.RestaurantInfoModel);
            var loadCars = _repositoryLoadCarRecovery.GetAll();
            if (beginTime.HasValue)//开始时间
                distributionDeails = distributionDeails.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)//结束时间
                distributionDeails = distributionDeails.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (!string.IsNullOrWhiteSpace(productName))//产品名称
                typeNubers = typeNubers.Where(o => o.Name.Contains(productName));

            if (!string.IsNullOrWhiteSpace(restaurant))//餐厅名称
                distributionDeails = distributionDeails.Where(o => o.RestaurantInfoModel.RestaurantName.Contains(restaurant));

            var data = typeNubers.GroupJoin(distributionDeails,
               t => t.Id,
               d => d.TypeNumberInfoId,
               (t1, d1) => new DistributionProductStatisticsDto
               {
                   TypeId = t1.Id,
                   ProductName = t1.Name,
                   DistributionCount = d1.Sum(o => o.Distributioncount),
                   DistributionSetCount = d1.Sum(o => o.Distributioncount * t1.Count),
                   ExchangegoodsCount = d1.Sum(o => o.Exchangegoodscount),
                   ExchangegoodsSetCount = d1.Sum(o => o.Exchangegoodscount * t1.Count),
                   GiveCount = d1.Sum(o => o.Givecount),
                   GiveSetCount = d1.Sum(o => o.Givecount * t1.Count),
                   RecoveryCount = d1.Sum(o => o.Recoverycount),
                   RecoverySetCount = d1.Sum(o => o.Recoverycount * t1.Count),
                   BackBoxCount = d1.Sum(o => o.Backboxcount),
                   BackNumberCount = d1.Sum(o => o.Backnumbercount) + d1.Sum(o => o.Backboxcount * t1.Count),
                   DamageCount = d1.Sum(o => o.Damagecount),
                   TotalPrice = d1.Sum(o => o.Sumprice)
               });
            //var data2 = data.GroupJoin(loadCars, d => d.TypeId, l => l.TypeNumberInfoId, (d1, l1) => new { d = d1, l = l1 });
            //List<DistributionProductStatisticsDto> list = new List<DistributionProductStatisticsDto>();
            //foreach (var item in data)
            //{
            //    item.d.RecoveryCount = item.l.Sum(l => l.Recoverycount);
            //    item.d.BackBoxCount = item.l.Sum(l => l.Backboxcount);
            //    item.d.BackNumberCount = item.l.Sum(l => l.Backnumbercount);
            //    item.d.DamageCount = item.l.Sum(l => l.Damagecount);

            //    list.Add(item.d);
            //}

            return data.ToList();
        }

        public async Task<DeliverySituationDto> GetDeliverySituationAsync(string restaurantName)
        {
            var user = await base.GetCurrentUserAsync();
            var restaurants = _repositoryRestaurantInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);


            ///得到最近8天的数据
            var distributions = _repositoryDistributionInfo.GetAll().Where(o => o.CreationTime >= DateTime.Now.AddDays(-7));
            var join = restaurants.GroupJoin(distributions,
                r => r.Id,
                d => d.Restaurantid,
                (r1, d1) => new
                {
                    Restaurant = r1,
                    Distributions = d1
                });

            var count = join.Count();

            DeliverySituationDto dto = new DeliverySituationDto();

            ///七天以上没有配送
            dto.OverSevenDays = join.Where(o => o.Distributions.Count() == 0).Count();//七天以上
                                                                                      //剩余3-7天未配送的


            //当天配送的餐厅
            dto.Nowadays = restaurants.GroupJoin(_repositoryDistributionInfo.GetAll().Where(d => EF.Functions.DateDiffDay(d.CreationTime, DateTime.Now) == 0),
               r => r.Id,
               d => d.Restaurantid, (r1, d1) => new
               {
                   Restaurant = r1,
                   Distributions = d1
               }).Where(o => o.Distributions.Count() != 0).Count();//今天已配送的餐厅数

            //去除大于7天没有配送的-减去当天的等于1-7天的配送


            dto.TwoDays = count - restaurants.GroupJoin(_repositoryDistributionInfo.GetAll().Where(d => EF.Functions.DateDiffDay(d.CreationTime, DateTime.Now) == 2),
                r => r.Id,
                d => d.Restaurantid, (r1, d1) => new
                {
                    Restaurant = r1,
                    Distributions = d1
                }).Where(o => o.Distributions.Count() == 0).Count();//三至七天未配送餐厅
                                                                    //两天未配送的餐厅数


            dto.OneDay = count - restaurants.GroupJoin(_repositoryDistributionInfo.GetAll().Where(d => EF.Functions.DateDiffDay(d.CreationTime, DateTime.Now) == 1),
                r => r.Id,
                d => d.Restaurantid, (r1, d1) => new
                {
                    Restaurant = r1,
                    Distributions = d1
                }).Where(o => o.Distributions.Count() == 0).Count();//三至七天未配送餐厅//一天未配送的餐厅数


            dto.ThreeToSevenDays = count - dto.OverSevenDays - dto.Nowadays - dto.OneDay - dto.TwoDays;
            return dto;

        }

        public async Task<IPagedList<DeliverySituationDetailsDto>> GetDeliverySituationDetailsAsync(int pageIdx, int pageSize, DeliveryTimeRange ramge)
        {

            var user = await base.GetCurrentUserAsync();
            var query = _repositoryRestaurantInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);

            var query2 = _repositoryDistributionInfo.GetAll().Where(o => o.CreationTime > DateTime.Now.AddDays(-8) && o.FactoryinfoId == user.FactoryinfoId);

            var sss = query.GroupJoin(query2,
               r => r.Id,
               d => d.Restaurantid,
               (r1, d1) => new
               {
                   Restaurant = r1,
                   Distributions = d1
               });


            var join = query.GroupJoin(query2,
                r => r.Id,
                d => d.Restaurantid,
                (r1, d1) => new
                {
                    RestaurantId = r1.Id,
                    RestaurantName = r1.RestaurantName,
                    RestaurantAddress = r1.RestaurantAddress,
                    EmployeeDriverid = r1.EmployeeDriverid,
                    RestaurantContact = r1.RestaurantContact,
                    Mobile = r1.Mobile,
                    Distributions = d1.Select(o => o.CreationTime),
                });

            var k = join.Where(o => o.Distributions.Where(d => d <= DateTime.Now.AddDays(-8)).Count() == 0);

            switch (ramge)
            {
                case DeliveryTimeRange.Nowadays:
                    join = join.Where(o => o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) == 0).Count() > 0);
                    break;
                case DeliveryTimeRange.OneDay:
                    join = k.Join(join.Where(o => o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) == 1).Count() > 0 && o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) == 0).Count() == 0), i => i.RestaurantId, b => b.RestaurantId, (i, b) => b).Where(o => o.Distributions.Count() > 0);
                    break;
                case DeliveryTimeRange.TwoDays:
                    join = k.Join(join.Where(o => o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) == 2).Count() > 0 //两天前有配送
                    && o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) < 2).Count() == 0)//今天和昨天没有配送
                        , i => i.RestaurantId, b => b.RestaurantId, (i, b) => b).Where(o => o.Distributions.Count() > 0);
                    break;
                case DeliveryTimeRange.ThreeToSevenDays:
                    join = k.Join(join.Where(o => o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) <= 7).Count() > 0//七天内有配送
                    && EF.Functions.DateDiffDay(o.Distributions.Max(), DateTime.Now) > 3)//三天内有配送
                    , i => i.RestaurantId, b => b.RestaurantId, (i, b) => b).Where(o => o.Distributions.Count() > 0);
                    break;
                case DeliveryTimeRange.OverSevenDays:
                    //join = join.Where(o => o.Distributions.Where(d => d <= DateTime.Now.AddDays(-7)).Count() == 0);
                    join = join.Where(o => o.Distributions.Where(d => EF.Functions.DateDiffDay(d, DateTime.Now) <= 7).Count() == 0);
                    break;
                default:
                    break;
            }


            var data = join.Join(_repositoryUser.GetAll(), i => i.EmployeeDriverid, j => j.Id, (i, j) => new DeliverySituationDetailsDto
            {
                RestaurantName = i.RestaurantName,//餐厅名称
                LastDeliveryTime = i.Distributions.Count() != 0 ? i.Distributions.DefaultIfEmpty(DateTime.Now.AddDays(-8)).Max(d => d) : new DateTime(),//最后配送时间
                LastDelivery = i.Distributions.Count() != 0 ? Math.Abs(i.Distributions.DefaultIfEmpty(DateTime.Now.AddDays(-8)).Max(d => d).Subtract(DateTime.Now).Days) + "天前" : "无配送记录",//最后配送
                DriverName = j.Name,//司机名称
                RestaurantContactsName = i.RestaurantContact,//餐厅负责人
                RestaurantContactsPhone = i.Mobile,//餐厅负责人联系电话
                RestaurantAddress = i.RestaurantAddress//餐厅地址

            });


            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            //var data2 = await data.ToPagedListAsync(pageIdx, pageSize);
            //sw.Stop();
            //TimeSpan ts2 = sw.Elapsed;
            //var t = ts2.TotalMilliseconds;


            return await data.ToPagedListAsync(pageIdx, pageSize);

        }

        public async Task<QuarterlySummaryDto> GetQuarterlySummary()
        {
            QuarterlySummaryDto dto = new QuarterlySummaryDto();
            dto.Summarys = new List<QuarterlySummaryDto.SummaryDto>();
            var user = await base.GetCurrentUserAsync();

            var queryModel = _repositoryReceiptInfoBySettlementModel.GetAll().Where(o => o.ToVoidStatus == ToVoidStatus.未作废 && (EF.Functions.DateDiffMonth(o.CreationTime, DateTime.Now) == 0 || EF.Functions.DateDiffMonth(o.CreationTime, DateTime.Now) == 1 || EF.Functions.DateDiffMonth(o.CreationTime, DateTime.Now) == 2) && o.FactoryinfoId == user.FactoryinfoId).GroupBy(o => new { Year = o.CreationTime.Year, Month = o.CreationTime.Month }).Select(s => new
            {
                Year = s.Key.Year,
                Month = s.Key.Month,
                YearMonth = s.Key.Year + s.Key.Month,
                TotalPrice = s.Sum(sum => sum.TaskBackAmount + sum.UsePrePayment + sum.PreferentialAmount)
            });

            dto.Summarys = await _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.RestaurantInfoModel).Where(o => (EF.Functions.DateDiffMonth(o.CreationTime, DateTime.Now) == 0 || EF.Functions.DateDiffMonth(o.CreationTime, DateTime.Now) == 1 || EF.Functions.DateDiffMonth(o.CreationTime, DateTime.Now) == 2) && o.RestaurantInfoModel.FactoryinfoId == user.FactoryinfoId).GroupBy(o => new { Year = o.CreationTime.Year, Month = o.CreationTime.Month }).Select(s => new
            {
                Year = s.Key.Year,
                Month = s.Key.Month,
                YearMonth = s.Key.Year + s.Key.Month,
                TotalPrice = s.Sum(sum => sum.TotalPrice),
                DistributionInfoListDetailsCount = s.SelectMany(o => o.DistributionInfoListDetails).Sum(sum => sum.Distributioncount)
            }).GroupJoin(queryModel, i => i.YearMonth, n => n.YearMonth, (i, b) => new QuarterlySummaryDto.SummaryDto
            {

                Year = i.Year,
                Month = i.Month,
                Distribution = i.DistributionInfoListDetailsCount,
                Receivable = i.TotalPrice,
                Already = b.Sum(sum => sum.TotalPrice)

            }).ToListAsync();

            //foreach (IGrouping<dynamic, DistributionInfo> item in qurey)
            //{
            //    decimal received = 0m;//已收
            //    decimal uncollected = 0m;//未收
            //    foreach (var i in item)
            //    {
            //        if (i.Pricestatus == Pricestatus.已结账)
            //        {
            //            received = received + i.TotalPrice;
            //        }
            //        else if (i.Pricestatus == Pricestatus.未结账 || i.Pricestatus == Pricestatus.已制单)
            //        {
            //            uncollected = uncollected + i.TotalPrice;
            //        }
            //    }
            //    dto.Summarys.Add(new QuarterlySummaryDto.SummaryDto { Year = item.Key.Year, Month = item.Key.Month, Distribution = item.Sum(o => o.DistributionInfoListDetails.Sum(s => s.Distributioncount)), Already = received, Receivable = uncollected });
            //}

            #region 今日汇总
            var qurey2 = await _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.RestaurantInfoModel).Where(o => (EF.Functions.DateDiffDay(o.CreationTime, DateTime.Now) == 0) && o.RestaurantInfoModel.FactoryinfoId == user.FactoryinfoId).Select(o => new { TodayDistribution = o.DistributionInfoListDetails.Sum(s => s.Distributioncount), TodayRecycling = o.DistributionInfoListDetails.Sum(s => s.Recoverycount), Status = o.Pricestatus, TotalPrice = o.TotalPrice }).ToListAsync();
            dto.TodaySummary = new QuarterlySummaryDto.TodaySummaryDto();


            dto.TodaySummary.TodayReceipt = _repositoryReceiptInfoBySettlementModel.GetAll().Where(o => o.ToVoidStatus == ToVoidStatus.未作废 && o.FactoryinfoId == user.FactoryinfoId && EF.Functions.DateDiffDay(o.CreationTime, DateTime.Now) == 0).Sum(sum => sum.TaskBackAmount + sum.UsePrePayment + sum.PreferentialAmount);

            //var loads = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId).Select(o => o.Id);//获取今日本工厂的装车信息Id

            ////通过装车Id获取今日的回收数量
            //var recovery = _repositoryLoadCarRecovery.GetAll().Where(o => (EF.Functions.DateDiffDay(o.CreationTime, DateTime.Now) == 0) && loads.Any(s => s == o.LoadCarId)).Sum(o => o.Recoverycount);

            // dto.TodaySummary.TodayRecycling = recovery;
            if (qurey2.Count > 0)
            {
                dto.TodaySummary.TodayDistribution = qurey2.Sum(o => o.TodayDistribution);
                dto.TodaySummary.TodayRecycling = qurey2.Sum(o => o.TodayRecycling);
            }
            #endregion
            return dto;
        }

        public async Task<List<QuarterlySummaryMonthDto>> GetQuarterlySummaryMonthData(DateTime time)
        {
            var user = await base.GetCurrentUserAsync();
            List<QuarterlySummaryMonthDto> list = new List<QuarterlySummaryMonthDto>();

            var queryModel = _repositoryReceiptInfoBySettlementModel.GetAll().Where(o => o.ToVoidStatus == ToVoidStatus.未作废 && EF.Functions.DateDiffMonth(o.CreationTime, time) == 0 && o.FactoryinfoId == user.FactoryinfoId).GroupBy(o => new { Year = o.CreationTime.Year, Month = o.CreationTime.Month, Day = o.CreationTime.Day }).Select(s => new
            {
                Year = s.Key.Year,
                Month = s.Key.Month,
                Day = s.Key.Day,
                YearMonthDay = s.Key.Year + s.Key.Month + s.Key.Day,
                TotalPrice = s.Sum(sum => sum.TaskBackAmount + sum.UsePrePayment + sum.PreferentialAmount)
            });


            list = await _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.RestaurantInfoModel).Where(o => o.RestaurantInfoModel.FactoryinfoId == user.FactoryinfoId && EF.Functions.DateDiffMonth(o.CreationTime, time) == 0).GroupBy(o => new { Year = o.CreationTime.Year, Month = o.CreationTime.Month, Day = o.CreationTime.Day }).Select(s => new
            {
                Year = s.Key.Year,
                Month = s.Key.Month,
                Day = s.Key.Day,
                YearMonthDay = s.Key.Year + s.Key.Month + s.Key.Day,
                DistributionInfoListDetailsCount = s.SelectMany(o => o.DistributionInfoListDetails).Sum(sum => sum.Distributioncount)
            }).GroupJoin(queryModel, i => i.YearMonthDay, j => j.YearMonthDay, (i, j) => new QuarterlySummaryMonthDto()
            {
                Date = i.Year + "-" + i.Month + "-" + i.Day,
                TotalDelivery = i.DistributionInfoListDetailsCount,
                TotalReceipts = j.Sum(o => o.TotalPrice),

            }).ToListAsync();



            //foreach (var item in query)
            //{
            //    QuarterlySummaryMonthDto dto = new QuarterlySummaryMonthDto() { Date = item.Key.Year + "-" + item.Key.Month + "-" + item.Key.Day, TotalDelivery = item.Sum(s => s.DistributionInfoListDetails.Sum(i => i.Distributioncount)), TotalReceipts = item.Where(o => o.Pricestatus == Pricestatus.已结账).Sum(o => o.TotalPrice) };

            //    list.Add(dto);
            //}

            return list;
        }

        public async Task<List<QuarterlySummaryDayDto>> GetQuarterlySummaryDayData(DateTime time, string type)
        {
            var user = await base.GetCurrentUserAsync();
            List<QuarterlySummaryDayDto> list = new List<QuarterlySummaryDayDto>();
            if (type == "Distribution")
            {
                var qurey = await _repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel, o => o.RestaurantInfoModel).Where(o => (EF.Functions.DateDiffDay(o.CreationTime, time) == 0) && o.RestaurantInfoModel.FactoryinfoId == user.FactoryinfoId).GroupBy(o => o.TypeNumberInfoModel).ToListAsync();

                foreach (var item in qurey)
                {
                    //var loadRecoverys = _repositoryLoadCarRecovery.GetAll().Where(o => o.TypeNumberInfoId == item.Key.Id).Sum(o=>o.Recoverycount);
                    QuarterlySummaryDayDto dto = new QuarterlySummaryDayDto() { ProductName = item.Key.Name, TotalDelivery = item.Sum(s => s.Distributioncount), TotalRecycling = item.Sum(s => s.Recoverycount) };
                    //dto.TotalRecycling = loadRecoverys;
                    list.Add(dto);
                }
            }
            else if (type == "Receipt")
            {
                var qurey = _repositoryDistributionInfo.GetAllIncluding(o => o.RestaurantInfoModel).Where(o => (EF.Functions.DateDiffDay(o.CreationTime, time) == 0) && o.RestaurantInfoModel.FactoryinfoId == user.FactoryinfoId && o.Pricestatus == Pricestatus.已结账).GroupBy(o => o.RestaurantInfoModel);

                foreach (var item in qurey)
                {
                    QuarterlySummaryDayDto dto = new QuarterlySummaryDayDto() { RestaurantName = item.Key.RestaurantName, ReceiptAmount = item.Sum(o => o.TotalPrice) };

                    list.Add(dto);
                }
            }


            return list;
        }

        public async Task<DriverActualRatioTotalDto> GetDriverActualRatioAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, long? keyword)
        {
            //当前登录人
            var user = await base.GetCurrentUserAsync();
            //司机
            var drivers = _repositoryUser.GetAll().Where(o => o.EmployeeType == EmployeeType.司机类型 && o.FactoryinfoId == user.FactoryinfoId);
            var restaurants = _repositoryRestaurantInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId && o.IsDiscontinuation == false);//餐厅

            if (endTime.HasValue)
                restaurants = restaurants.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (keyword.HasValue)
                restaurants = restaurants.Where(o => o.EmployeeDriverid == keyword.Value);

            var distribution = _repositoryDistributionInfo.GetAll();
            //if (month.HasValue)
            //    distribution = distribution.Where(o => EF.Functions.DateDiffMonth(o.CreationTime, month.Value) == 0);
            if (beginTime.HasValue)
                distribution = distribution.Where(o => o.CreationTime >= beginTime);
            if (endTime.HasValue)
                distribution = distribution.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (keyword.HasValue)
                drivers = drivers.Where(o => o.Id == keyword.Value);

            var cars = _repositoryCarInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);

            var query1 = drivers.GroupJoin(restaurants, d => d.Id, r => r.EmployeeDriverid, (d, r) => new
            {
                d.Id
            }).Join(cars, d => d.Id, c => c.EmployeeCarUserId, (d, c) => new
            {

                CarId = c.Id,
            }).Join(distribution, d1 => d1.CarId, d2 => d2.Carinfoid, (d1, d2) => new
            {

                d2.CreationTime,
                d2.Restaurantid
            }).GroupBy(q => new { q.CreationTime.Year, q.CreationTime.Month, q.CreationTime.Day });


            var data = query1.Select(o => new DriverActualRatioOutputDto()
            {
                ShouldSend = restaurants.Count(),
                DistributionDate = new DateTime(o.Key.Year, o.Key.Month, o.Key.Day),
                ActualSnd = o.Select(s => s.Restaurantid).Distinct().Count(),
            });

            DriverActualRatioTotalDto dto = new DriverActualRatioTotalDto();
            dto.TotalActualSnd = data.Sum(o => o.ActualSnd);
            dto.TotalShouldSend = data.Sum(o => o.ShouldSend);
            dto.DriverActualRatioPagedList = await data.OrderByDescending(o => o.DistributionDate).ToPagedListAsync(pageIdx, pageSize);

            return dto;
        }

        public async Task<List<DriverActualRatioOutputDto>> GetExportDriverActualRatioAsync(DateTime? beginTime, DateTime? endTime, long? keyword)
        {
            //当前登录人
            var user = await base.GetCurrentUserAsync();
            //司机
            var drivers = _repositoryUser.GetAll().Where(o => o.EmployeeType == EmployeeType.司机类型 && o.FactoryinfoId == user.FactoryinfoId);
            var restaurants = _repositoryRestaurantInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);//餐厅
            var distribution = _repositoryDistributionInfo.GetAll();
            //if (month.HasValue)
            //    distribution = distribution.Where(o => EF.Functions.DateDiffMonth(o.CreationTime, month.Value) == 0);
            if (beginTime.HasValue)
                distribution = distribution.Where(o => o.CreationTime >= beginTime);
            if (endTime.HasValue)
                distribution = distribution.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (keyword.HasValue)
                drivers = drivers.Where(o => o.Id == keyword.Value);

            var cars = _repositoryCarInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            var query1 = drivers.GroupJoin(restaurants, d => d.Id, r => r.EmployeeDriverid, (d, r) => new
            {
                d.Id,
                ShouldSend = r.Count()
            }).Join(cars, d => d.Id, c => c.EmployeeCarUserId, (d, c) => new
            {
                d.Id,
                d.ShouldSend,
                CarId = c.Id,
            }).Join(distribution, d1 => d1.CarId, d2 => d2.Carinfoid, (d1, d2) => new
            {
                d1.ShouldSend,
                d2.CreationTime,
                d2.Restaurantid
            }).GroupBy(q => new { q.CreationTime.Year, q.CreationTime.Month, q.CreationTime.Day });

            var data = query1.Select(o => new DriverActualRatioOutputDto()
            {
                ShouldSend = o.Sum(s => s.ShouldSend),
                DistributionDate = new DateTime(o.Key.Year, o.Key.Month, o.Key.Day),
                ActualSnd = o.Select(s => s.Restaurantid).Distinct().Count(),
            });

            return data.OrderByDescending(o => o.DistributionDate).ToList();
        }

        public async Task<List<MonthReportChartOutputDto>> GetDistributionReportChart(DateTime time, DateSearchType type)
        {
            string sql = "";
            DateTime firstDay = new DateTime();
            DateTime lastDay = new DateTime();
            var user = await base.GetCurrentUserAsync();
            switch (type)
            {
                case DateSearchType.Month:
                    firstDay = time.AddDays(1 - time.Day);
                    lastDay = firstDay.AddMonths(1).AddDays(-1);

                    sql = string.Format(@"select b.Days,ISNULL(sum(a.Distributioncount),0) as DeliveryNumber from (select convert(varchar(10),dateadd(day,number,'{0}'),120)  as Days from master..spt_values 
                        where datediff(day,dateadd(day,number,'{0}'), '{1}')>=0 and number>=0  and type='p')b
                        left join (select d.CreationTime,d.Distributioncount,d.Recoverycount from dbo.DistributionInfoDetails d left join dbo.RestaurantInfo r on d.Restaurantid=r.Id  where d.IsDeleted=0 and r.FactoryinfoId='{2}') a on  CONVERT(varchar(100), a.CreationTime, 23)=b.Days  group by b.Days", firstDay, lastDay, user.FactoryinfoId);
                    break;
                case DateSearchType.Year:
                    firstDay = new DateTime(time.Year, 1, 1);
                    lastDay = firstDay.AddYears(1).AddDays(-1);

                    sql = string.Format(@"select b.Days,ISNULL(sum(a.Distributioncount),0) as DeliveryNumber from (select  left(convert(varchar(10),dateadd(MONTH,number,'{0}'),120),7)  as Days from master..spt_values 
                        where datediff(MONTH,dateadd(MONTH,number,'{0}'), '{1}')>=0 and number>=0  and type='p')b
                        left join (select d.CreationTime,d.Distributioncount,d.Recoverycount from dbo.DistributionInfoDetails d left join dbo.RestaurantInfo r on d.Restaurantid=r.Id  where d.IsDeleted=0 and r.FactoryinfoId='{2}') a on left(CONVERT(varchar(100), a.CreationTime, 23),7)=b.Days  group by b.Days", firstDay, lastDay, user.FactoryinfoId);
                    break;
                default:
                    break;
            }


            var data = _sqlExecuter.FromSqlQuery<MonthReportChartOutputDto>(sql, null);

            return data.ToList();
        }


        public async Task<List<TypeReportChartOutputDto>> GetTypeDistributionReportData(DateTime time, DateSearchType type)
        {
            DateTime firstDay = new DateTime();
            DateTime lastDay = new DateTime();

            if (type == DateSearchType.Month)
            {
                firstDay = time.AddDays(1 - time.Day);
                lastDay = firstDay.AddMonths(1).AddDays(-1);
            }
            else
            {
                firstDay = new DateTime(time.Year, 1, 1);
                lastDay = firstDay.AddYears(1).AddDays(-1);
            }

            var user = await base.GetCurrentUserAsync();
            var types = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            var distributions = _repositoryDistributionInfoDetails.GetAll().Where(o => o.CreationTime >= firstDay && o.CreationTime <= lastDay);

            var query = types.GroupJoin(distributions, t => t.Id, d => d.TypeNumberInfoId,
                (t1, d1) => new TypeReportChartOutputDto
                {
                    TypeName = t1.Name,
                    DeliveryNumber = d1.Sum(o => o.Distributioncount)
                });

            return query.ToList();


        }

        public async Task<List<DriverReportChartOutputDto>> GetDriverDistributionReportData(DateTime time, DateSearchType type)
        {
            DateTime firstDay = new DateTime();
            DateTime lastDay = new DateTime();

            if (type == DateSearchType.Month)
            {
                firstDay = time.AddDays(1 - time.Day);
                lastDay = firstDay.AddMonths(1).AddDays(-1);
            }
            else
            {
                firstDay = new DateTime(time.Year, 1, 1);
                lastDay = firstDay.AddYears(1).AddDays(-1);
            }
            var user = await base.GetCurrentUserAsync();
            var drivers = _repositoryUser.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId && o.EmployeeType == EmployeeType.司机类型);
            var distributions = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.RestaurantInfoModel).Where(o => o.CreationTime >= firstDay && o.CreationTime <= lastDay);

            var query = drivers.GroupJoin(distributions, d => d.Id, t => t.RestaurantInfoModel.EmployeeDriverid, (d1, d2) => new DriverReportChartOutputDto
            {
                DriverName = d1.Name,
                DeliveryNumber = d2.Sum(o => o.Distributioncount)
            });

            return query.ToList();
        }

        public async Task<List<DistributionAndRecyclingOutputDto>> GetDistributionAndRecyclingReportData(DateTime time, DateSearchType type)
        {
            var user = await base.GetCurrentUserAsync();
            string sql = "";
            DateTime firstDay = new DateTime();
            DateTime lastDay = new DateTime();

            switch (type)
            {
                case DateSearchType.Month:
                    firstDay = time.AddDays(1 - time.Day);
                    lastDay = firstDay.AddMonths(1).AddDays(-1);
                    sql = string.Format(@"select b.Days as GroupName,ISNULL(sum(a.Distributioncount),0) as Distribution ,ISNULL(SUM(a.Recoverycount),0) as Recovered from (select convert(varchar(10),dateadd(day,number,'{0}'),120)  as Days from master..spt_values 
                        where datediff(day,dateadd(day,number,'{0}'), '{1}')>=0 and number>=0  and type='p')b
                        left join (select d.CreationTime,d.Distributioncount,d.Recoverycount from dbo.DistributionInfoDetails d left join dbo.RestaurantInfo r on d.Restaurantid=r.Id  where d.IsDeleted=0 and r.FactoryinfoId='{2}') a on  CONVERT(varchar(100), a.CreationTime, 23)=b.Days  group by b.Days", firstDay, lastDay, user.FactoryinfoId);
                    break;
                case DateSearchType.Year:
                    firstDay = new DateTime(time.Year, 1, 1);
                    lastDay = firstDay.AddYears(1).AddDays(-1);
                    sql = string.Format(@"select b.Days as GroupName,ISNULL(sum(a.Distributioncount),0) as Distribution ,ISNULL(SUM(a.Recoverycount),0) as Recovered from (select  left(convert(varchar(10),dateadd(MONTH,number,'{0}'),120),7)  as Days from master..spt_values 
                        where datediff(MONTH,dateadd(MONTH,number,'{0}'), '{1}')>=0 and number>=0  and type='p')b
                        left join (select d.CreationTime,d.Distributioncount,d.Recoverycount from dbo.DistributionInfoDetails d left join dbo.RestaurantInfo r on d.Restaurantid=r.Id  where d.IsDeleted=0 and r.FactoryinfoId='{2}') a on left(CONVERT(varchar(100), a.CreationTime, 23),7)=b.Days  group by b.Days", firstDay, lastDay, user.FactoryinfoId);
                    break;
                default:
                    break;
            }

            var data = _sqlExecuter.FromSqlQuery<DistributionAndRecyclingOutputDto>(sql, null);

            return data.ToList();
        }

        public async Task<List<DistributionAndRecyclingOutputDto>> GetDistributionAndRecyclingByDriverReportData(DateTime time)
        {
            var user = await base.GetCurrentUserAsync();
            DateTime firstDay = time.AddDays(1 - time.Day);
            DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);

            var drivers = _repositoryUser.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId && o.EmployeeType == EmployeeType.司机类型);
            var distributions = _repositoryDistributionInfoDetails.GetAllIncluding(o => o.RestaurantInfoModel).Where(o => o.CreationTime >= firstDay && o.CreationTime <= lastDay);

            var query = drivers.GroupJoin(distributions, d => d.Id, t => t.RestaurantInfoModel.EmployeeDriverid, (d1, d2) => new DistributionAndRecyclingOutputDto
            {
                GroupName = d1.Name,
                Distribution = d2.Sum(o => o.Distributioncount),
                Recovered = d2.Sum(o => o.Recoverycount)
            });

            return query.ToList();
        }



        public async Task<HomeTodayStatisticsOutputDto> GetHomeTodayStatistics()
        {
            var user = await base.GetCurrentUserAsync();
            var qurey = await _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.RestaurantInfoModel).Where(o => (EF.Functions.DateDiffDay(o.CreationTime, DateTime.Now) == 0) && o.RestaurantInfoModel.FactoryinfoId == user.FactoryinfoId).Select(o => new { TodayDistribution = o.DistributionInfoListDetails.Sum(s => s.Distributioncount), TodayRecycling = o.DistributionInfoListDetails.Sum(s => s.Recoverycount), Status = o.Pricestatus, TotalPrice = o.TotalPrice, Restaurant = o.Restaurantid }).ToListAsync();

            HomeTodayStatisticsOutputDto dto = new HomeTodayStatisticsOutputDto();
            if (qurey.Count > 0)
            {
                dto.Distribution = qurey.Sum(o => o.TodayDistribution);
                dto.Recovered = qurey.Sum(o => o.TodayRecycling);
                //dto.Receipt = qurey.Sum(o => o.TotalPrice);
                dto.RestaurantCount = qurey.Select(o => o.Restaurant).Distinct().Count();
            }

            dto.Receipt = _repositoryReceiptInfoBySettlementModel.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId && o.ToVoidStatus == ToVoidStatus.未作废 && EF.Functions.DateDiffDay(o.CreationTime, DateTime.Now) == 0).Sum(o => o.TaskBackAmount + o.UsePrePayment + o.PreferentialAmount);

            return dto;
        }

        public async Task<List<DistributionDetailsListViewDto>> GetDetailsListAsync(string restaurantName, string driverId, DateTime? beginTime, DateTime? endTime)
        {
            var listmodel = DistributionDetailsCatche.AsQueryable();

            if (!string.IsNullOrEmpty(restaurantName))
                listmodel = listmodel.Where(o => o.RestaurantName.Contains(restaurantName));
            if (!string.IsNullOrEmpty(driverId))
                listmodel = listmodel.Where(o => o.DriverId.ToString() == driverId);
            if (beginTime.HasValue)
                listmodel = listmodel.Where(o => o.DistributionDate >= beginTime);
            if (endTime.HasValue)
                listmodel = listmodel.Where(o => o.DistributionDate <= endTime.Value.AddHours(24));

            var list = listmodel.GroupBy(o => o.CreationNumber);

            List<DistributionDetailsListViewDto> detailsList = new List<DistributionDetailsListViewDto>();

            foreach (var item in list)
            {
                DistributionDetailsListViewDto dto = new DistributionDetailsListViewDto();
                if (item.Count() > 0)
                {
                    dto.CreationNumber = item.First().CreationNumber;
                    dto.DistributionDate = item.First().DistributionDate;
                    dto.RestaurantName = item.First().RestaurantName;
                    dto.DriverId = item.First().DriverId;
                    dto.DriverName = item.First().DriverName;
                    dto.PlatesNumber = item.First().PlatesNumber;

                    dto.DistributionDetailLists = new List<DistributionDetailsModel>();
                    foreach (var temp in item)
                    {
                        DistributionDetailsModel model = new DistributionDetailsModel()
                        {
                            TypeNumberName = temp.TypeNumberName,
                            TypeNumberPrice=temp.TypeNumberPrice,
                            Distributioncount = temp.Distributioncount,
                            DistributionBycount = temp.DistributionBycount,
                            Damagecount = temp.Damagecount,
                            Givecount = temp.Givecount,
                            GiveBycount = temp.GiveBycount,
                            Backboxcount = temp.Backboxcount,
                            Backnumbercount = temp.Backnumbercount,
                            Exchangegoodscount = temp.Exchangegoodscount,
                            ExchangegoodsBycount = temp.ExchangegoodsBycount,
                            Recoverycount = temp.Recoverycount,
                            RecoveryBycount = temp.RecoveryBycount,
                            SumPrice = temp.SumPrice
                        };
                        dto.DistributionDetailLists.Add(model);
                    }
                }
                detailsList.Add(dto);
            }

            return await detailsList.ToListAsync();
        }

        #endregion
        #endregion
        #region 后台缓存
        private Task<List<DistributionInfo>> GetCache
        {
            get
            {
                ICache cache = _catchmanager.GetCache(nameof(DistributionInfo));
                return cache.GetAsync($"list", async () => await _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails, o => o.CarInfoModel, o => o.RestaurantInfoModel).ToListAsync());
            }

        }
        #endregion
        private Task<List<LoadCar>> GetLoadCarCache
        {
            get
            {
                ICache cache = _catchmanager.GetCache(nameof(LoadCar));
                return cache.GetAsync($"list", async () => await _repositoryLoadCar.GetAllIncluding(o => o.CarInfoModel, o => o.LoadingCarInfoList).OrderByDescending(m => m.CreationTime).ToListAsync());
            }
        }
        #region 配送
        private List<DistributionViewDto> LoadCarCatch
        {
            get
            {
                var usermodel = _repositoryUser.Get(AbpSession.UserId.Value);
                ICache cache = _catchmanager.GetCache(nameof(DistributionViewDto));
                return cache.Get($"list_{usermodel.FactoryinfoId}", () => DistributionViewDtoCatch(usermodel).ToList());
            }
        }
        private IQueryable<DistributionViewDto> DistributionViewDtoCatch(User usermodel)
        {

            string sql = $@"select [Id]
                                  ,[CarInfoId]
                                  ,[CreationNumber]
                                  ,[CarStatus]
                                  ,[BackStatus]
                                  ,[ExamineStatus]
                                  ,[CreationTime]
                                  ,[CreatorUserId]
                                  ,[CarType]
                                  ,[PlatesNumber]
                                  ,[FactoryinfoId]
                                  ,[Name]
                                  ,[Mobile]
                                  ,[Countproduct]
                                  ,[RestaurantInfoCount] from V_LoadCar where FactoryinfoId='{usermodel.FactoryinfoId}' order by CreationTime desc";
            return _sqlExecuter.FromSqlQuery<DistributionViewDto>(sql, null);
        }

        #endregion

        #region 应收查询
        private List<ReceivableDto> BillDetailsCatch
        {
            get
            {
                var usermodel = _repositoryUser.Get(AbpSession.UserId.Value);
                ICache cache = _catchmanager.GetCache(nameof(ReceivableDto));
                return cache.Get($"list_{usermodel.FactoryinfoId}", () => ReceivableDtoCatch(usermodel).ToList());
            }
        }
        private IQueryable<ReceivableDto> ReceivableDtoCatch(User usermodel)
        {
            string sql = $@"select [Id]
                                  ,[CreationTime]
                                  ,[CreatorUserId]
                                  ,[RestaurantName]
                                  ,[RestaurantAddress]
                                  ,[FactoryinfoId]
                                  ,[Pricestatus]
                                  ,[TotalPrice]
                                  ,[PlatesNumber]
                                  ,[DriverName]
                                  ,[DriverMobile] from V_BillDetails where FactoryinfoId='{usermodel.FactoryinfoId}' order by CreationTime desc";

            return _sqlExecuter.FromSqlQuery<ReceivableDto>(sql, null);
        }
        #endregion

        #region 配送单
        private List<DistributionDetailsView> DistributionInfoCatch
        {
            get
            {
                var usermodel = _repositoryUser.Get(AbpSession.UserId.Value);

                ICache cache = _catchmanager.GetCache(nameof(DistributionDetailsView));
                return cache.Get($"list_{usermodel.FactoryinfoId}", () => DistributionDetailsViewCatch(usermodel).ToList());
            }
        }
        private IQueryable<DistributionDetailsView> DistributionDetailsViewCatch(User usermodel)
        {
            string sql = $@"select [Id]
                                      ,[CreatorUserId]
                                      ,[CreationNumber]
                                      ,[CreationTime]
                                      ,[DistributionStock]
                                      ,[Stock]
                                      ,[PlatesNumber]
                                      ,[Name]
                                      ,[Mobile]
                                      ,[FactoryinfoId]
                                      ,[Pricestatus]
                                      ,[CarStatus]
                                      ,[ExamineStatus]
                                      ,[BackStatus]
                                      ,[RestaurantId]
                                      ,[RestaurantAddress]
                                      ,[RestaurantName]
                                      ,[TotalPrice]
                                      ,[Backboxcount]
                                      ,[Backnumbercount]
                                      ,[Damagecount]
                                      ,[Distributioncount]
                                      ,[Exchangegoodscount]
                                      ,[Givecount]
                                      ,[Recoverycount]
                                      ,[BackboxBycount]
                                      ,[BacknumberBycount]
                                      ,[Damagebycount]
                                      ,[DistributionBycount]
                                      ,[RecoveryBycount]
                                      ,[ExchangegoodsBycount]
                                      ,[Givebycount]
                                      ,[SettlementId]
                                      ,[SettlementTime] from V_DistributionInfo where FactoryinfoId='{usermodel.FactoryinfoId}' order by CreationTime desc";

            return _sqlExecuter.FromSqlQuery<DistributionDetailsView>(sql, null);
        }
        /// <summary>
        /// 配送单明细
        /// </summary>
        private List<DistributionDetailsListView> DistributionDetailsCatche
        {
            get
            {
                var usermodel = _repositoryUser.Get(AbpSession.UserId.Value);

                ICache cache = _catchmanager.GetCache(nameof(DistributionDetailsListView));
                return cache.Get($"list_{usermodel.FactoryinfoId}", () => DistributionDetailsListViewCatch(usermodel).ToList());
            }
        }
        private IQueryable<DistributionDetailsListView> DistributionDetailsListViewCatch(User usermodel)
        {
            string sql = $@"select CreationNumber,
                                   a.CreationTime as DistributionDate,
                                   RestaurantName,
                                   a.CreatorUserId as DriverId,
                                   a.Name as DriverName,
                                   PlatesNumber,
                                   a.Stock Stock,
                                   c.Name as TypeNumberName,
                                   b.Distributioncount,
                                   b.TypeNumberPrice,
                                   (b.Distributioncount*c.Count) as DistributionBycount,
                                   b.Recoverycount,
                                   (b.Recoverycount*c.Count) as RecoveryBycount,
                                   b.Exchangegoodscount,
                                   (b.Exchangegoodscount*c.Count) as ExchangegoodsBycount,
                                   b.Damagecount,
                                   b.Givecount,
                                   (b.Givecount*c.Count) as GiveBycount,
                                   b.Backboxcount,
                                   b.Backnumbercount,
                                   b.Sumprice from V_DistributionInfo a,DistributionInfoDetails b,TypeNumberInfo c where a.id=b.DistributionInfoId and b.TypeNumberInfoId = c.Id and a.FactoryinfoId='{usermodel.FactoryinfoId}' order by a.CreationTime desc";

            return _sqlExecuter.FromDapperSqlQuery<DistributionDetailsListView>(sql, null).AsQueryable();
        }
        #endregion

        #region 餐厅配送统计
        //private List<RestaurantDistributionView> RestaurantDistributionCatch
        //{
        //    get
        //    {

        //        ICache cache = _catchmanager.GetCache(nameof(RestaurantDistributionView));
        //        return cache.Get($"list_{usermodel.FactoryinfoId}", () => model.ToList());
        //    }
        //}
        #endregion

        #region 获取型号单价为0的餐厅列表
        private List<RestaurantTypeNumberViewDto> RestaurantTypeNumberCatche
        {
            get
            {
                var usermodel = _repositoryUser.Get(AbpSession.UserId.Value);
                ICache cache = _catchmanager.GetCache(nameof(RestaurantTypeNumberViewDto));
                return cache.Get($"list_{usermodel.FactoryinfoId}", () => RestaurantTypeNumberViewCatch(usermodel).ToList());
            }
        }
        [Obsolete("此Sql方法已作废不再使用")]
        private IQueryable<RestaurantTypeNumberViewDto> RestaurantTypeNumberViewCatch(User usermodel)
        {
            string sql = $@"select b.Id as RestaurantTypeNumberId,
                                           RestaurantName,
                                           RestaurantAddress,
                                           a.RestaurantContact as Name,a.Mobile,
                                           e.Name as TypeNumberName,
                                           Price from RestaurantInfo a,RestaurantTypenNumberInfo b,RestaurantUserInfo c,TypeNumberInfo e where a.Id = b.Restaurantid and a.id=c.RestaurantInfoId and b.TypeNumberId = e.Id and b.IsDeleted=0 and b.Price=0 and a.FactoryinfoId='{usermodel.FactoryinfoId}'";

            return _sqlExecuter.FromDapperSqlQuery<RestaurantTypeNumberViewDto>(sql, null).AsQueryable();
        }
        #endregion

        #region 可生成收据的配送信息
        public async Task<IPagedList<GenerateReceiptOutputDto>> GetGenerateReceiptListAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, string restaurantName, long? driverId, Guid? Line2)
        {
            var user = await base.GetCurrentUserAsync();
            //获取当前时间段的所有配送
            var query1 = _repositoryDistributionInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId && o.SettlementId.HasValue == false);
            if (beginTime.HasValue)
                query1 = query1.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                query1 = query1.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            //根据司机查询出餐厅
            var re = _repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && o.BalanceWay == BalanceWayEnum.定期结算);
            if (driverId.HasValue)
            {
                re = re.Where(o => o.EmployeeDriverid == driverId);//配送人就是司机
            }
            else if (Line2.HasValue)
            {
                var lineUsers = _repositoryLoadDriverLine.GetAll().Where(o => o.LineId == Line2).Select(o => o.DriverId);
                re = re.Where(o => lineUsers.Any(s => s == o.EmployeeDriverid));

            }

            ///根据配送记录left 所有的餐厅信息
            var b = query1.Join(re, i => i.Restaurantid, k => k.Id, (i, k) => new
            {
                k.Id,
                i.TotalPrice,
                k.RestaurantName,
                k.BalanceCycle,
                k.Stock
            });
            if (!string.IsNullOrEmpty(restaurantName))
                b = b.Where(o => o.RestaurantName.Contains(restaurantName));

            ///根据餐厅分组获取餐厅的所有金额
            return await b.GroupBy(t => t.Id).Select(m => new
            {
                Id = m.Key,
                Amount = m.Sum(s => s.TotalPrice)
            }).Join(_repositoryRestaurantInfo.GetAll().Where(o => o.BalanceWay == BalanceWayEnum.定期结算), i => i.Id, k => k.Id, (i, k) => new GenerateReceiptOutputDto
            {

                Id = k.Id,
                RestaurantName = k.RestaurantName,
                BalanceCycle = k.BalanceCycle,
                Amount = i.Amount,
                Principal = k.RestaurantContact,
                Mobile = k.Mobile
            }).ToPagedListAsync(pageIdx, pageSize);

        }

        public async Task<List<GenerateReceiptOutputDto>> GetExportGenerateReceiptListAsync(DateTime? beginTime, DateTime? endTime, string restaurantName, long? driverId, Guid? Line2)
        {
            var user = await base.GetCurrentUserAsync();
            //获取当前时间段的所有配送
            var query1 = _repositoryDistributionInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId && o.SettlementId.HasValue == false);
            if (beginTime.HasValue)
                query1 = query1.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                query1 = query1.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (driverId.HasValue)
            {
                query1 = query1.Where(o => o.CreatorUserId == driverId);//配送人就是司机
            }
            else if (Line2.HasValue)
            {
                var lineUsers = _repositoryLoadDriverLine.GetAll().Where(o => o.LineId == Line2).Select(o => o.DriverId);
                query1 = query1.Where(o => lineUsers.Any(s => s == o.CreatorUserId));

            }

            ///根据配送记录left 所有的餐厅信息
            var b = query1.Join(_repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && o.BalanceWay == BalanceWayEnum.定期结算), i => i.Restaurantid, k => k.Id, (i, k) => new
            {
                k.Id,
                i.TotalPrice,
                k.RestaurantName,
                k.BalanceCycle,
                k.Stock
            });
            if (!string.IsNullOrEmpty(restaurantName))
                b = b.Where(o => o.RestaurantName.Contains(restaurantName));

            ///根据餐厅分组获取餐厅的所有金额
            return await b.GroupBy(t => t.Id).Select(m => new
            {
                Id = m.Key,
                Amount = m.Sum(s => s.TotalPrice)
            }).Join(_repositoryRestaurantInfo.GetAll().Where(o => o.BalanceWay == BalanceWayEnum.定期结算), i => i.Id, k => k.Id, (i, k) => new GenerateReceiptOutputDto
            {

                Id = k.Id,
                RestaurantName = k.RestaurantName,
                BalanceCycle = k.BalanceCycle,
                Amount = i.Amount,
                Principal = k.RestaurantContact,
                Mobile = k.Mobile
            }).ToListAsync();

        }

        public async Task<List<MakingReceiptOutputDto>> GetMakingReceiptsAsync(Guid? driverLine, string ids, DateTime beginTime, DateTime endTime, int type = 0, long driverId = 0, string remarks = "")
        {
            var user = await base.GetCurrentUserAsync();
            List<Guid> guid = new List<Guid>();
            var data = new List<MakingReceiptOutputDto>();
            ///type 表示查询餐厅不等于0表示线路1
            if (type == 0)
            {
                if (driverId != 0)
                {

                    guid = _repositoryRestaurantInfo.GetAll().Where(o => o.EmployeeDriverid == driverId && o.FactoryinfoId == user.FactoryinfoId && o.BalanceWay == BalanceWayEnum.定期结算).Select(o => o.Id).ToList();
                }
                else
                {
                    if (!string.IsNullOrEmpty(ids))
                    {
                        foreach (var item in ids.Split('|'))
                        {
                            guid.Add(new Guid(item));
                        }
                    }
                }

            }
            else if (type == 1)//选择某条线路
            {
                if (driverLine.HasValue)
                {
                    var lineUsers = _repositoryLoadDriverLine.GetAll().Where(o => o.LineId == driverLine).Select(o => o.DriverId);
                    guid = _repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && lineUsers.Any(s => s == o.EmployeeDriverid) && o.FactoryinfoId == user.FactoryinfoId && o.BalanceWay == BalanceWayEnum.定期结算).Select(o => o.Id).ToList();
                }
            }
            else if (type == 2)//全部餐厅
            {
                guid = _repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && o.FactoryinfoId == user.FactoryinfoId && o.BalanceWay == BalanceWayEnum.定期结算).Select(o => o.Id).ToList();
            }
            else if (type == 3)//半月定期
            {
                guid = _repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && o.FactoryinfoId == user.FactoryinfoId && o.BalanceCycle == BalanceCycleEnum.半月定期 && o.BalanceWay == BalanceWayEnum.定期结算).Select(o => o.Id).ToList();
            }
            else if (type == 4)//每月定期
            {
                guid = _repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && o.FactoryinfoId == user.FactoryinfoId && o.BalanceCycle == BalanceCycleEnum.每月定期 && o.BalanceWay == BalanceWayEnum.定期结算).Select(o => o.Id).ToList();
            }

            //得到餐厅信息
            var b = guid.Join(_repositoryRestaurantInfo.GetAll().Where(o => o.IsDiscontinuation == false && o.BalanceWay == BalanceWayEnum.定期结算), i => i, k => k.Id, (i, k) => new
            {
                k.Id,
                k.RestaurantName,
                k.BalanceCycle,
                k.Stock
            }).GroupJoin(_repositoryDistributionInfoDetails.GetAllIncluding(o => o.TypeNumberInfoModel).Where(o => o.PricesId == Guid.Empty && o.CreationTime >= beginTime && o.CreationTime <= endTime.AddHours(24)).GroupBy(t => new { t.Restaurantid, t.TypeNumberInfoId, t.TypeNumberPrice, t.TypeNumberName }).Select(o => new
            {
                Rmodel = o.Key,
                Price = o.Sum(s => s.Sumprice),
                Quantity = o.Sum(s => (s.Distributioncount - s.Backboxcount) * s.TypeNumberInfoModel.Count - (s.Damagecount + s.Backnumbercount))
            }).Join(_repositoryTypeNumberInfo.GetAll(), i => i.Rmodel.TypeNumberInfoId, k => k.Id, (i, k) => new
            {
                i.Rmodel,
                i.Price,
                i.Quantity,
                OnePriceCount = k.Count,
            }), i => i.Id, k => k.Rmodel.Restaurantid, (i, k) => new
            {
                i.Id,
                i.RestaurantName,
                i.BalanceCycle,
                i.Stock,
                TypeNumberModel = k,
                Total = k.Sum(s => s.Price),
            }).Where(o => o.TypeNumberModel.Count() > 0);

            //Dictionary<Guid, List<Guid>> sListGuid = new Dictionary<Guid, List<Guid>>();
            foreach (var item in b)
            {
                //SettlementInfo model = new SettlementInfo()
                //{
                //    Id = _guid.Create(),
                //    FactoryinfoId = user.FactoryinfoId,
                //    Restaurantid = item.Id,
                //    Totalprice = item.Total,
                //    Discountprice = 0m,
                //    Actualprice = item.Total,
                //    DeliveryDate = beginTime.ToString("yyyy-MM-dd") + " 至 " + endTime.ToString("yyyy-MM-dd"),
                //    BeginTime = beginTime,
                //    EndTime = endTime,
                //    RemarksConten = remarks
                //};

                ////修改所有关联的配送详情的结账状态
                //var modellist = _repositoryDistributionInfo.GetAll().Where(o => o.SettlementId.HasValue == false && o.Restaurantid == item.Id && o.CreationTime >= beginTime && o.CreationTime <= endTime.AddHours(24));
                //sListGuid.Add(model.Id, modellist.Select(o => o.Id).ToList());

                //await _repositorySettlementInfo.InsertAndGetIdAsync(model).ContinueWith((obj) => {
                //    Task.Factory.StartNew(() =>
                //    {
                //        var c = obj.Result;
                //        var eventDate = new RemoteEventData(RemoteTypeHelp.TypeSettlementInfo)
                //        {
                //            Data = { [RemoteTypeHelp.ListT] = sListGuid }
                //        };
                //        remoteEventBus.Publish(RemoteTypeHelp.TopicSettlementInfo, eventDate);

                //    });

                //});
                var entity = new MakingReceiptOutputDto
                {
                    //Id = model.Id,
                    RestaurantId = item.Id,
                    RestaurantName = item.RestaurantName,
                    BeginTime = beginTime,
                    EndTime = endTime,
                    Sum = item.Total,
                    Capital = CapitalHelper.CmycurD(item.Total),
                    RemarksConten = remarks,
                    Suits = item.TypeNumberModel.Select(o => new SuitDto
                    {
                        TypeNumberId = o.Rmodel.TypeNumberInfoId.Value,
                        Name = o.Rmodel.TypeNumberName,
                        //Price = o.Rmodel.TypeNumberPrice * o.OnePriceCount,
                        Price = o.Rmodel.TypeNumberPrice,
                        Quantity = o.Quantity,
                        Total = o.Price
                    }).ToList(),
                    IsZeroCount = item.TypeNumberModel.Where(o => o.Price == 0m).Count()

                };
                data.Add(entity);
            }

            return data;

        }
        #endregion

        #region 应收汇总
        public async Task<TotalSummaryReceivableDto> GetSummaryReceivablePagesListAsync(int pageIdx, int pageSize, DateTime? beginTime, DateTime? endTime, long? DriverId, Guid? Line, RestaurantPayStatus? PayStatus, BalanceWayEnum? WayEnum, string keyword)
        {
            var user = await base.GetCurrentUserAsync();

            #region 1
            //var m = _repositoryDistributionInfo.GetAllIncluding(r => r.RestaurantInfoModel);
            //if (beginTime != null)
            //    m = m.Where(o => o.CreationTime >= beginTime);

            //if (endTime.HasValue)
            //    m = m.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            //var query2 = _repositoryDistributionInfoDetails.GetAll().Where(o => o.PricesId != Guid.Empty);
            //if (beginTime != null)
            //    query2 = query2.Where(o => o.CreationTime >= beginTime);

            //if (endTime.HasValue)
            //    query2 = query2.Where(o => o.CreationTime <= endTime.Value.AddHours(24));



            //var details = query2.GroupBy(t => new { t.Restaurantid, t.TypeNumberInfoId, t.TypeNumberPrice, t.TypeNumberName }).Select(o => new
            //{
            //    Rmodel = o.Key,
            //    DistributionCount = o.Sum(s => s.Distributioncount),
            //    RecoveryCount = o.Sum(s => s.Recoverycount),
            //    GiveCount = o.Sum(s => s.Givecount),
            //    ExchangegoodsCount = o.Sum(s => s.Exchangegoodscount),
            //    DistributionPrice = o.Sum(s => s.Sumprice)
            //});

            //var settlementInfosList = _repositorySettlementInfo.GetAllIncluding(o => o.RestaurantInfoModel).Where(o => o.FactoryinfoId == user.FactoryinfoId && o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核 && o.RestaurantPayStatus != RestaurantPayStatus.已确认);

            //var k = m.GroupBy(o => o.Restaurantid).Select(s => new
            //{
            //    RestaurantId = s.Key,
            //    TotalPrice = s.Sum(o => o.TotalPrice),
            //    SettlementInfoIds = s.Select(o => o.SettlementId),
            //}).Join(_repositoryRestaurantInfo.GetAll(), i => i.RestaurantId, j => j.Id, (i, j) => new {

            //    RestaurantId = i.RestaurantId,
            //    RestaurantName = j.RestaurantName,
            //    TotalPrice = i.TotalPrice,
            //    SettlementInfoIds = i.SettlementInfoIds,
            //}).GroupJoin(details, i => i.RestaurantId, s => s.Rmodel.Restaurantid, (i, s) => new
            //{
            //    RestaurantId = i.RestaurantId,
            //    RestaurantName = i.RestaurantName,
            //    TotalPrice = i.TotalPrice,
            //    TypeNumbers = s,
            //    SettlementInfoIds = i.SettlementInfoIds.Join(settlementInfosList, v => v.Value, n => n.Id, (v, n) => new
            //    {
            //        SettlementInfoIds = new
            //        {
            //            Restaurantid = n.Restaurantid,
            //            TotalDiscount = n.ReceivedDiscount + n.Discountprice,
            //            ReceivedDiscount = n.ReceivedDiscount,
            //            Actualprice = n.Actualprice,
            //            Totalprice = n.Totalprice,
            //            ReceivedPrice = n.ReceivedPrice
            //        }

            //    }).GroupBy(g => g.SettlementInfoIds.Restaurantid).Select(se => new
            //    {
            //        TotalDiscount = se.Sum(sum => sum.SettlementInfoIds.TotalDiscount),
            //        ReceivedDiscount = se.Sum(sum => sum.SettlementInfoIds.ReceivedDiscount)
            //    })
            //});

            //var data = await k.Select(o => new SummaryReceivableOutputDto
            //{
            //    //Id=o.RestaurantId.Value,
            //    RestaurantName = o.RestaurantName,
            //    DistributionPrice = o.TotalPrice,
            //    TotalDiscount = o.SettlementInfoIds.Sum(s => s.TotalDiscount),
            //    SummaryDistributions = o.TypeNumbers.Select(s => new SummaryDistribution
            //    {
            //        TypeNumberName = s.Rmodel.TypeNumberName,
            //        DistributionCount = s.DistributionCount,
            //        ExchangegoodsCount = s.ExchangegoodsCount,
            //        GiveCount = s.GiveCount,
            //        RecoveryCount = s.RecoveryCount
            //    }).ToList()
            //}).ToPagedListAsync(pageIdx, pageSize);

            //return data;

            #endregion

            var distributionquery = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.FactoryinfoId == user.FactoryinfoId);
            if (beginTime.HasValue)
                distributionquery = distributionquery.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                distributionquery = distributionquery.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (WayEnum.HasValue)
                distributionquery = distributionquery.Where(o => o.RestaurantInfoModel.BalanceWay == WayEnum);

            if (!string.IsNullOrEmpty(keyword))
                distributionquery = distributionquery.Where(o => o.RestaurantInfoModel.RestaurantName.Contains(keyword));

            ///应收汇总应该查询配送表的配送司机
            if (DriverId.HasValue)
                distributionquery = distributionquery.Where(o => o.CreatorUserId == DriverId);

            if (Line.HasValue && Line != Guid.Empty)//线路
            {
                var lineUsers = _repositoryLoadDriverLine.GetAll().Where(o => o.LineId == Line).Select(o => o.DriverId);
                distributionquery = distributionquery.Where(o => lineUsers.Any(s => s == o.CreatorUserId));
            }


            var settlemenquery = _repositorySettlementInfo.GetAll().Where(o => o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核);

            if (DriverId.HasValue)
                settlemenquery = settlemenquery.Where(o => o.EmployeeDriverid == DriverId);


            if (PayStatus.HasValue)
                settlemenquery = settlemenquery.Where(o => o.RestaurantPayStatus == PayStatus.Value);


            #region MyRegion
            //var query2 = distributionquery.GroupBy(o => o.PricesId);


            #endregion

            var t = distributionquery.SelectMany(o => o.DistributionInfoListDetails).GroupBy(s => new { s.Restaurantid, s.TypeNumberInfoId, s.TypeNumberName }).Select(s => new
            {
                Id = s.Key.Restaurantid,
                TypeNumberInfoId = s.Key.TypeNumberInfoId,
                TypeNumberName = s.Key.TypeNumberName,
                DistributionCount = s.Sum(x => x.Distributioncount),
                ExchangegoodsCount = s.Sum(x => x.Exchangegoodscount),
                GiveCount = s.Sum(x => x.Givecount),
                RecoveryCount = s.Sum(x => x.Recoverycount)
            });
            ///首先根据配送信息查询出所有的收据信息
            var set = distributionquery.Select(s => new { SettlementId = s.SettlementId }).Join(settlemenquery.Select(sb => new { Id = sb.Id }), i => i.SettlementId, n => n.Id, (i, n) => new
            {
                i.SettlementId
            }).Distinct().Join(settlemenquery.Select(s => new
            {
                s.Id,
                s.Restaurantid,
                s.RestaurantPayStatus,
                s.Totalprice,
                s.UsePrePayment,
                s.ReceivedDiscount,
                s.ReceivedPrice,
                s.Actualprice,
                s.Discountprice

            }), i => i.SettlementId, n => n.Id, (i, n) => new
            {
                n.Restaurantid,
                n.RestaurantPayStatus,
                n.Totalprice,
                n.UsePrePayment,
                n.ReceivedDiscount,
                n.ReceivedPrice,
                n.Actualprice,
                n.Discountprice
            }).GroupBy(g => new { g.Restaurantid }).Select(s => new
            {
                Restaurantid = s.Key.Restaurantid.Value,
                Actualprice = s.Sum(j => j.Actualprice),
                Discountprice = s.Sum(j => j.Discountprice),
                TotalPrice = s.Sum(j => j.Totalprice),
                ReceivedDiscount = s.Sum(j => j.ReceivedDiscount),
                UsePrePayment = s.Sum(j => j.UsePrePayment),
                ReceivedPrice = s.Sum(j => j.ReceivedPrice),
                Discount = s.Sum(j => j.Discountprice + j.ReceivedDiscount)
            });

            var query = distributionquery.AsQueryable().Select(s => new { s.Restaurantid, s.TotalPrice }).GroupBy(o => new { o.Restaurantid }).Select(s => new
            {
                RestaurantId = s.Key.Restaurantid,
                Sumprice = s.Sum(o => o.TotalPrice)//配送金额
            }).Join(_repositoryRestaurantInfo.GetAll().Select(n => new { n.Id, n.RestaurantName }), i => i.RestaurantId, n => n.Id, (i, n) => new
            {
                RestaurantId = i.RestaurantId,
                RestaurantName = n.RestaurantName,
                Sumprice = i.Sumprice
            }).GroupJoin(set, i => i.RestaurantId, j => j.Restaurantid, (i, j) => new
            {
                RestaurantId = i.RestaurantId,
                RestaurantName = i.RestaurantName,
                Sumprice = i.Sumprice,//配送金额
                Actualprice = j.Sum(s => s.Actualprice),
                Discountprice = j.Sum(s => s.Discountprice),
                TotalPrice = j.Sum(s => s.TotalPrice),
                ReceivedDiscount = j.Sum(s => s.ReceivedDiscount),
                UsePrePayment = j.Sum(s => s.UsePrePayment),
                ReceivedPrice = j.Sum(s => s.ReceivedPrice),
                Discount = j.Sum(s => s.Discount)
            }).GroupJoin(t, o => o.RestaurantId, n => n.Id, (o, n) => new SummaryReceivableOutputDto
            {
                Id = o.RestaurantId.Value,
                RestaurantName = o.RestaurantName,
                DistributionPrice = o.Sumprice,
                TotalDiscount = o.Discount,
                Actualprice = o.Actualprice,
                UsePrePayment = o.UsePrePayment,
                ReceivedPrice = o.ReceivedPrice,
                SummaryDistributions = n.Select(s => new SummaryDistribution
                {
                    TypeNumberName = s.TypeNumberName,
                    DistributionCount = s.DistributionCount,
                    ExchangegoodsCount = s.ExchangegoodsCount,
                    GiveCount = s.GiveCount,
                    RecoveryCount = s.RecoveryCount
                }).ToList()
            });



            var pagelist = await query.ToPagedListAsync(pageIdx, pageSize);


            // var model = new TotalSummaryReceivableDto();
            var model = (await query.AsParallel().GroupBy(g => 0).Select(s => new TotalSummaryReceivableDto
            {
                TotalDistributionPrice = s.Sum(sum => sum.DistributionPrice),
                TotalSummaryPrice = s.Sum(o => o.DistributionPrice - o.TotalDiscount),
                TotalDiscountPrice = s.Sum(o => o.TotalDiscount),
                TotalReceivedPrice = s.Sum(o => o.ReceivedPrice),
                //TotalNotActualprice = s.Sum(o => o.DistributionPrice - o.TotalDiscount - o.Actualprice - o.UsePrePayment),
                TotalUsePrePayment = s.Sum(o => o.UsePrePayment),
                TotalDistributionCount = s.Sum(o => o.SummaryDistributions.Sum(x => x.DistributionCount)),
                TotalRecoveryCount = s.Sum(o => o.SummaryDistributions.Sum(x => x.RecoveryCount)),
                TotalGiveCount = s.Sum(o => o.SummaryDistributions.Sum(x => x.GiveCount)),
                TotalExChangedCount = s.Sum(o => o.SummaryDistributions.Sum(x => x.ExchangegoodsCount)),
            }).ToListAsync())?.FirstOrDefault();

            if (model == null)
            {
                model = new TotalSummaryReceivableDto();
            }
            model.PageList = pagelist;
            // var data = query.ToList();


            return model;
        }
        /// <summary>
        /// 应收汇总导出
        /// </summary>
        /// <returns></returns>
        public async Task<List<SummaryReceivableOutputDto>> GetExportSummaryReceivableListAsync(DateTime? beginTime, DateTime? endTime, long? DriverId, Guid? Line, RestaurantPayStatus? PayStatus, BalanceWayEnum? WayEnum, string keyword)
        {
            var user = await base.GetCurrentUserAsync();

            var distributionquery = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.FactoryinfoId == user.FactoryinfoId);
            if (beginTime.HasValue)
                distributionquery = distributionquery.Where(o => o.CreationTime >= beginTime);

            if (endTime.HasValue)
                distributionquery = distributionquery.Where(o => o.CreationTime <= endTime.Value.AddHours(24));

            if (WayEnum.HasValue)
                distributionquery = distributionquery.Where(o => o.RestaurantInfoModel.BalanceWay == WayEnum);

            if (!string.IsNullOrEmpty(keyword))
                distributionquery = distributionquery.Where(o => o.RestaurantInfoModel.RestaurantName.Contains(keyword));

            var settlemenquery = _repositorySettlementInfo.GetAll().Where(o => o.ExamineStatus == Core.SettlementInfoModel.ExamineStatus.已审核);

            if (DriverId.HasValue)
                settlemenquery = settlemenquery.Where(o => o.EmployeeDriverid == DriverId);

            if (Line.HasValue && Line != Guid.Empty)//线路
            {
                var lineUsers = _repositoryLoadDriverLine.GetAll().Where(o => o.LineId == Line).Select(o => o.DriverId);
                settlemenquery = settlemenquery.Where(o => lineUsers.Any(s => s == o.EmployeeDriverid));
            }

            if (PayStatus.HasValue)
                settlemenquery = settlemenquery.Where(o => o.RestaurantPayStatus == PayStatus.Value);

            var t = distributionquery.SelectMany(o => o.DistributionInfoListDetails).GroupBy(s => new { s.Restaurantid, s.TypeNumberInfoId, s.TypeNumberName }).Select(s => new
            {
                Id = s.Key.Restaurantid,
                TypeNumberInfoId = s.Key.TypeNumberInfoId,
                TypeNumberName = s.Key.TypeNumberName,
                DistributionCount = s.Sum(x => x.Distributioncount),
                ExchangegoodsCount = s.Sum(x => x.Exchangegoodscount),
                GiveCount = s.Sum(x => x.Givecount),
                RecoveryCount = s.Sum(x => x.Recoverycount)
            });
            ///首先根据配送信息查询出所有的收据信息
            var set = distributionquery.Select(s => new { SettlementId = s.SettlementId }).Join(settlemenquery.Select(sb => new { Id = sb.Id }), i => i.SettlementId, n => n.Id, (i, n) => new
            {
                i.SettlementId
            }).Distinct().Join(settlemenquery.Select(s => new
            {
                s.Id,
                s.Restaurantid,
                s.RestaurantPayStatus,
                s.Totalprice,
                s.UsePrePayment,
                s.ReceivedDiscount,
                s.ReceivedPrice,
                s.Actualprice,
                s.Discountprice

            }), i => i.SettlementId, n => n.Id, (i, n) => new
            {
                n.Restaurantid,
                n.RestaurantPayStatus,
                n.Totalprice,
                n.UsePrePayment,
                n.ReceivedDiscount,
                n.ReceivedPrice,
                n.Actualprice,
                n.Discountprice
            }).GroupBy(g => new { g.Restaurantid }).Select(s => new
            {
                Restaurantid = s.Key.Restaurantid.Value,
                Actualprice = s.Sum(j => j.Actualprice),
                Discountprice = s.Sum(j => j.Discountprice),
                TotalPrice = s.Sum(j => j.Totalprice),
                ReceivedDiscount = s.Sum(j => j.ReceivedDiscount),
                UsePrePayment = s.Sum(j => j.UsePrePayment),
                ReceivedPrice = s.Sum(j => j.ReceivedPrice),
                Discount = s.Sum(j => j.Discountprice + j.ReceivedDiscount)
            });

            var query = distributionquery.AsQueryable().Select(s => new { s.Restaurantid, s.TotalPrice }).GroupBy(o => new { o.Restaurantid }).Select(s => new
            {
                RestaurantId = s.Key.Restaurantid,
                Sumprice = s.Sum(o => o.TotalPrice)//配送金额
            }).Join(_repositoryRestaurantInfo.GetAll().Select(n => new { n.Id, n.RestaurantName }), i => i.RestaurantId, n => n.Id, (i, n) => new
            {
                RestaurantId = i.RestaurantId,
                RestaurantName = n.RestaurantName,
                Sumprice = i.Sumprice
            }).GroupJoin(set, i => i.RestaurantId, j => j.Restaurantid, (i, j) => new
            {
                RestaurantId = i.RestaurantId,
                RestaurantName = i.RestaurantName,
                Sumprice = i.Sumprice,//配送金额
                Actualprice = j.Sum(s => s.Actualprice),
                Discountprice = j.Sum(s => s.Discountprice),
                TotalPrice = j.Sum(s => s.TotalPrice),
                ReceivedDiscount = j.Sum(s => s.ReceivedDiscount),
                UsePrePayment = j.Sum(s => s.UsePrePayment),
                ReceivedPrice = j.Sum(s => s.ReceivedPrice),
                Discount = j.Sum(s => s.Discount)
            }).GroupJoin(t, o => o.RestaurantId, n => n.Id, (o, n) => new SummaryReceivableOutputDto
            {
                Id = o.RestaurantId.Value,
                RestaurantName = o.RestaurantName,
                DistributionPrice = o.Sumprice,
                TotalDiscount = o.Discount,
                Actualprice = o.Actualprice,
                UsePrePayment = o.UsePrePayment,
                ReceivedPrice = o.ReceivedPrice,
                SummaryDistributions = n.Select(s => new SummaryDistribution
                {
                    TypeNumberName = s.TypeNumberName,
                    DistributionCount = s.DistributionCount,
                    ExchangegoodsCount = s.ExchangegoodsCount,
                    GiveCount = s.GiveCount,
                    RecoveryCount = s.RecoveryCount
                }).ToList()
            });

            return query.ToList();
        }

        #endregion

    }
}
